javascripthtmljqueryformsonfocus

Make the first form field of a group active onfocus of div


I'm not sure if I worded the title correctly to describe my issue.

I am constructing a custom phone number 'field' within a form on my website, which is actually composed of 10 individual fields (digits), all grouped within a particular div (Id=numberContainer).

Currently, I am using some script to force the cursor to start at the first field (Id=userPhone_digit-01), no matter which field within the group the user clicks on.

The code also advances the cursor to the next 'digit' after data is entered into each field.

The code seems to work fine for all of that so far.

However, I would like to expand or modify the code, to have the cursor also start on the first field (Id=userPhone_digit-01) when the user clicks anywhere at all within the entire div (Id=numberContainer) or any elements within the div.

I have experimented with several 'tweaks', including some 'onfocus' things. But so far, I can't seem to get anything to work.

I have included a very stripped down version of the form, containing only the 'phone number' field(s).

I also left the link to the CSS in the 'head' section'.

I left out my failed attempts at tweaking the code and left in only what is currently working.

If anyone has any suggestions, it would be greatly appreciated.

Thanks, Maddison

HTML

<!DOCTYPE html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">

<link rel="stylesheet" href="https://www.jamiesexton.com/css/forcefield3.css">

</head>

<body>


<div class="pageContainer">

<div class="blankSpace"></div>

<div class="formContainer">

<form id="requestForm" action="/formHandler.php" method="post" enctype="multipart/form-data">


<div class="center_Wrapper">

<div class="formHeader">- THE FORM -</div>

</div>


<div class="phoneNumber_Container">

<div class="left_Wrapper">

<div class="section_Header">Phone Number</div>

<button class="phoneReset_button" title="Reset"><img src="/images/refreshbutton.png" 
width="20px" height="20px"></button>

</div>


<!-- //////////////////// Start 'numberContainer' Div //////////////////// -->


<div Id="numberContainer" class="phoneField_Wrapper">

<div class="leftSpace"><img 
src="https://www.jamiesexton.com/images/smallflag.jpg" width="40px" 
height="24px"></div>

<p class="plusOne">+1</p>

<p class="phoneNumber_Parentheses_Left">(</p>

<input type="number" id="userPhone_digit-01" name="userPhone_digit-01" class="phoneField" 
minlength="1" maxlength="1" tabindex="2"  required>

<input type="number" id="userPhone_digit-02" name="userPhone_digit-02" class="phoneField" 
minlength="1" maxlength="1" tabindex="3"  required>

<input type="number" id="userPhone_digit-03" name="userPhone_digit-03" class="phoneField" 
minlength="1" maxlength="1" tabindex="4"  required>

<p class="phoneNumber_Parentheses_Right">)</p>

<input type="number" id="userPhone_digit-04" name="userPhone_digit-04" class="phoneField4" 
minlength="1" maxlength="1" tabindex="5"  required>

<input type="number" id="userPhone_digit-05" name="userPhone_digit-05" class="phoneField" 
minlength="1" maxlength="1" tabindex="6"  required>

<input type="number" id="userPhone_digit-06" name="userPhone_digit-06" class="phoneField" 
minlength="1" maxlength="1" tabindex="7"  required>

<p class="phoneNumber_Dash">-</p>

<input type="number" id="userPhone_digit-07" name="userPhone_digit-07" class="phoneField" 
minlength="1" maxlength="1" tabindex="8"  required>

<input type="number" id="userPhone_digit-08" name="userPhone_digit-08" class="phoneField" 
minlength="1" maxlength="1" tabindex="9"  required>

<input type="number" id="userPhone_digit-09" name="userPhone_digit-09" class="phoneField" 
minlength="1" maxlength="1" tabindex="10" required>

<input type="number" id="userPhone_digit-10" name="userPhone_digit-10" class="phoneField" 
minlength="1" maxlength="1" tabindex="11" required>

<div class="rightSpace"></div>

</div>


<!-- //////////////////// End 'numberContainer' Div //////////////////// -->

</div>





<!-- Start Force-Field/Next-Field Script -->

<script>

const

forceField  = document.querySelector('#requestForm')
, f_nums = [...forceField.querySelectorAll('#numberContainer input')]
;

forceField.oninput = e =>
{

if ( e.target.matches('#numberContainer input[maxlength="1"]')
&& e.target.value.length===1 
){
let nextOneIndx = f_nums.findIndex(el=>el===e.target) +1;
if (nextOneIndx < f_nums.length)
  {
  f_nums[nextOneIndx].focus();
  }
else
  {
  let nextTab = +e.target.getAttribute('tabindex') +1;
  forceField.querySelector(`[tabindex="${nextTab}"]`).focus();
  }
}
}


forceField.onclick = e =>
{
if ( e.target.matches('#numberContainer input[maxlength="1"]')
&& e.target.value.length===0
){ 
let freeOne = f_nums.find(el=>el.value==='');  // find 1st input free
if (freeOne) freeOne.focus()
}
}

</script>

<!-- End Force-Field/Next-Field Script -->





<!-- Start Clear-Number-Fields Script -->

<script>

let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('.phoneField,.phoneField4');
btnClear.addEventListener('click', () => {
inputs.forEach(input =>  input.value = '');
});

</script>

<!-- End Clear-Number-Fields Script -->





<div class="submitButton_Container">

<div class="center_Wrapper" ><input type="submit" class="submit__button" value="Submit"></div>

</div>

</form>
</div>
</div>   
</body>
</html>

Solution

  • Query the numberContainer so you add an onclick event listener. Then onclick get the closest numberContainer, just in case event target is a child of the numberContainer element, we can then query the first input element using the number container element like this e.target.closest('#numberContainer').querySelector('#userPhone_digit-01')

    Then any time the user clicks anywhere on the number container element, the first input will focus.

    const numCont = document.getElementById('numberContainer')
    
    numCont.onclick = e => e.target.closest('#numberContainer').querySelector('#userPhone_digit-01').focus()
    

    const forceField = document.querySelector('#requestForm'),
      f_nums = [...forceField.querySelectorAll('#numberContainer input')];
      
    const numCont = document.getElementById('numberContainer')
    
    numCont.onclick = e => e.target.closest('#numberContainer').querySelector('#userPhone_digit-01').focus()
    
    
    forceField.oninput = e => {
      if (e.target.matches('#numberContainer input[maxlength="1"]') &&
        e.target.value.length === 1
      ) {
        let nextOneIndx = f_nums.findIndex(el => el === e.target) + 1;
        if (nextOneIndx < f_nums.length) {
          f_nums[nextOneIndx].focus();
        } else {
          let nextTab = +e.target.getAttribute('tabindex') + 1;
          forceField.querySelector(`[tabindex="${nextTab}"]`).focus();
        }
      }
    }
    
    
    forceField.onclick = e => {
      if (e.target.matches('#numberContainer input[maxlength="1"]') &&
        e.target.value.length === 0
      ) {
        let freeOne = f_nums.find(el => el.value === ''); // find 1st input free
        if (freeOne) freeOne.focus()
      }
    }
    
    let btnClear = document.querySelector('button');
    let inputs = document.querySelectorAll('.phoneField,.phoneField4');
    btnClear.addEventListener('click', () => {
      inputs.forEach(input => input.value = '');
    });
    <link rel="stylesheet" href="https://www.jamiesexton.com/css/forcefield3.css">
    
    
    
    <div class="pageContainer">
    
      <div class="blankSpace"></div>
    
      <div class="formContainer">
    
        <form id="requestForm" action="/formHandler.php" method="post" enctype="multipart/form-data">
    
    
          <div class="center_Wrapper">
    
            <div class="formHeader">- THE FORM -</div>
    
          </div>
    
    
          <div class="phoneNumber_Container">
    
            <div class="left_Wrapper">
    
              <div class="section_Header">Phone Number</div>
    
              <button class="phoneReset_button" title="Reset"><img src="/images/refreshbutton.png" 
    width="20px" height="20px"></button>
    
            </div>
    
    
            <!-- //////////////////// Start 'numberContainer' Div //////////////////// -->
    
    
            <div id="numberContainer" class="phoneField_Wrapper">
    
              <div class="leftSpace"><img src="https://www.jamiesexton.com/images/smallflag.jpg" width="40px" height="24px"></div>
    
              <p class="plusOne">+1</p>
    
              <p class="phoneNumber_Parentheses_Left">(</p>
    
              <input type="number" id="userPhone_digit-01" name="userPhone_digit-01" class="phoneField" minlength="1" maxlength="1" tabindex="2" required>
    
              <input type="number" id="userPhone_digit-02" name="userPhone_digit-02" class="phoneField" minlength="1" maxlength="1" tabindex="3" required>
    
              <input type="number" id="userPhone_digit-03" name="userPhone_digit-03" class="phoneField" minlength="1" maxlength="1" tabindex="4" required>
    
              <p class="phoneNumber_Parentheses_Right">)</p>
    
              <input type="number" id="userPhone_digit-04" name="userPhone_digit-04" class="phoneField4" minlength="1" maxlength="1" tabindex="5" required>
    
              <input type="number" id="userPhone_digit-05" name="userPhone_digit-05" class="phoneField" minlength="1" maxlength="1" tabindex="6" required>
    
              <input type="number" id="userPhone_digit-06" name="userPhone_digit-06" class="phoneField" minlength="1" maxlength="1" tabindex="7" required>
    
              <p class="phoneNumber_Dash">-</p>
    
              <input type="number" id="userPhone_digit-07" name="userPhone_digit-07" class="phoneField" minlength="1" maxlength="1" tabindex="8" required>
    
              <input type="number" id="userPhone_digit-08" name="userPhone_digit-08" class="phoneField" minlength="1" maxlength="1" tabindex="9" required>
    
              <input type="number" id="userPhone_digit-09" name="userPhone_digit-09" class="phoneField" minlength="1" maxlength="1" tabindex="10" required>
    
              <input type="number" id="userPhone_digit-10" name="userPhone_digit-10" class="phoneField" minlength="1" maxlength="1" tabindex="11" required>
    
              <div class="rightSpace"></div>
    
            </div>
    
    
            <!-- //////////////////// End 'numberContainer' Div //////////////////// -->
    
          </div>
    
    
    
    
    
          <div class="submitButton_Container">
    
            <div class="center_Wrapper"><input type="submit" class="submit__button" value="Submit"></div>
    
          </div>
    
        </form>
      </div>
    </div>