How to focus input from a form constantly?

Asked

Viewed 484 times

2

I have a form and need to focus on an input again until it satisfies the required, example:

$('#text1').blur(function() {
  var teste = $('#text1').val().length;
  console.log(teste);
  if(teste > 5){
    $('#text1').focus();
  }else{
    $('#text2').focus();
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
Input 1:
<input type="text" name="text1" id="text1">
</label>
<br><br>
<label>
Input 2:
<input type="text" name="text2" id="text2">
</label>

It is possible to proceed in this way?

  • What would be the problem?

  • Good morning Paulo, the problem was with the page load, because this form comes from json and as it was using an external js with some functions the same did not work accordingly and Focus() as well as other functions of jquery did not work, I copied the js functions below the form and it worked. I’ll try to figure out why to put a response.

  • 1

    maybe you were trying to execute the code of Focus before including jQuery in your page, you must be sure that jQuery is being included before (above) than the codes, otherwise it won’t work at all. and I also suggest that the code be within a $(document).ready(function(){ }); This ensures that the event will only be assigned to the element after it is already created. And if it is created with Ajax, you can run the codes in the method .done() ajax running when ajax ends.

1 answer

2


In that case you should use the .phocus since the .Blur works only to detect when the element loses focus.

$('#text2').focus(function() {
  $('#text1').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>
Input 1:
<input type="text" name="text1" id="text1">
</label>
<br><br>
<label>
Input 2:
<input type="text" name="text2" id="text2">
</label>

  • I cannot understand why this answer has been marked as correct, after all it produces the same result as the way the question is asked. In fact the form that is in the question is much more correct, because whenever the user clicks outside the field or clicks on another field or press tab, will always return to focus the field in question, and this way that is in this answer you can take the focus by clicking outside the field.

  • My answer was based on the question before it was edited, that’s how I understood it. He wanted that even if the user clicking on another input, the focus would remain on only one of it. With the editing of the question, just use it. Focus and . Blur.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.