Search code examples
javascripthtmljqueryfocus

How to focus a textbox via Javascript/Jquery locating in a collapsed section?


I have designed a web form including some questions and text boxes / areas for users to enter their answers using a single HTML table.

The questions are categorized, each category has a "clickable" category title, so when the title is clicked whole the questions inside the category are collapsed or expanded.

There are validations applied to some questions, I would like to "focus" to a specific textbox when the answer is not valid. I am able to do it via:

if(answer not valid) {document.getElementById('myTextBox').focus();}

however it only works when the category is already expanded, otherwise focus is not working.

Please see an example on the jsFiddle below. Click the "submit" button without typing an answer having more than 10 letters, you'd see it focuses to the textbox as long as the category is expanded. Please click on the category title "Project Details" to collapse it, then click the submit button again, the focus is not very helpful in this case as the questions of the category is not visible.

I want a category to auto-expanded and the regarding textbox is focused, where the answer is not valid. If there are multiple invalid answers, it is OK to focus on the very first one. Any help would be appreciated.

https://jsfiddle.net/Balkanlii/Lt914jvw/2/


Solution

  • You can simply show text before focusing

    $('.clickable').click(function() {
      $(this).find('span').text(function(_, value) {
        return value == '-' ? '+' : '-'
      });
      $(this).nextUntil('tr.clickable').slideToggle(100, function() {});
    });
    
    function validate() {
      if (document.getElementById('MainContent_txtProjectTitle').value.length <= 10) {
       $('#trProjectDetails').nextUntil('tr.clickable').show(100);
        document.getElementById('MainContent_txtProjectTitle').focus();
      }
    }
    tr.clickable {
      cursor: pointer;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
    
      <tr class="clickable" id="trProjectDetails">
        <td>
          <h4>Project Details <span>-</span></h4>
        </td>
      </tr>
      <tr>
        <td>
          <span id="spanQ1">1. Describe the project's outcome in one sentence.</span>
        </td>
      </tr>
      <tr>
        <td>
          <input name="txtProjectTitle" type="text" id="MainContent_txtProjectTitle" placeholder="min. 10 characters" style="width: 10em;">
        </td>
      </tr>
    
    </table><br />
    <input type="submit" name="btnSubmit" value="Submit" onclick="return validate();" id="MainContent_btnSubmit">