简体   繁体   中英

Focus on next div when valid radio selection or text input has been made

I have a form. Whenever a user hits the enter key on a text input, or when they tap or click on a radio button, I want to be able to set the focus to the next "formItem" div.

The structure of my form is set up like this:

  <div class="formItem" ng-class="{'invalidField' : calculate.wasSkipped(calculationForm.nonsustainedVT)}">
    <ng-form name="nonsustainedVT" novalidate>
      <div class="header"><span class="title">3) Nonsustained VT </span></div>
      <div class="content">
        <div class="radioGroup">

          <div class="radio-wrapper">
            <input id="nonsustainedVTYes" type="radio" required name="nonsustainedVT" ng-value="true" ng-model="calculate.formData.nonsustainedVT" ng-click tabindex="4">
          </div>

          <div class="label-wrapper">
            <label for="nonsustainedVTYes">Yes</label>
          </div>
        </div>
        <div class="radioGroup">

          <div class="radio-wrapper">
            <input id="nonsustainedVTNo" type="radio" required name="nonsustainedVT" ng-value="false" ng-model="calculate.formData.nonsustainedVT" ng-click tabindex="5">
          </div>

          <div class="label-wrapper">
            <label for="nonsustainedVTNo">No</label>
          </div>
          <span class="radioValidationHack!" ng-show="false">{{calculate.formData.nonsustainedVT}}</span>
        </div>
      </div>
    </ng-form>
  </div> 

Every input has a tabindex, so I was considering using this somehow, but once a user has made a selection I do not wish to necessarily just move the focus to the next tabindex because it may be in the same radio group. I wish to set the focus to the next "formItem" div.

Please see the following Plunkr for a larger code example: http://plnkr.co/edit/FQzOFEZLi6ReAuJninxA?p=preview

You don't need tab index, you can use the order of the tab items inside the form. I would make a myFormItem directive like this:

directive('myFormItem', function() {
  return {
    link: function(scope, element, attr) {
      var form = element.closest('form'),
        items = form.find('[my-form-item]'),
        index = items.index(element),
        nextFormItem = $(items[index+1]);

      element.find('input[type=radio]').on('click', function() {
        nextFormItem.find('input').focus();
      });

      element.find('input[type=text]').on('keypress', function(e) {
        if (e.which === 13) {
          nextFormItem.find('input').focus();
        }
      });
    }
  };
});

and you need to add the my-form-item attribute to each .formItem (btw, you should probably use kebab-case for classes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM