How to count the number of characters entered and the action on it?

Hi I am pretty simple in jQuery and stuck in a script:

//hide all radio buttons first $('#q11_6_1').parent().hide(); $('#q11_6_2').parent().hide(); $('#q11_6_3').parent().hide(); $('#q11_6_4').parent().hide(); $('#q11_6_5').parent().hide(); //check the length of the open text box var other2text = $('#q11_6_other').val().length; $('#q11_6_other').keypress(function(){ //if at least one character has been entered, then I want to show all radio buttons if(other2text>=0) { $('#q11_6_1').parent().show(); $('#q11_6_2').parent().show(); $('#q11_6_3').parent().show(); $('#q11_6_4').parent().show(); $('#q11_6_5').parent().show(); } //else I want to hide all else { $('#q11_6_1').parent().hide(); $('#q11_6_2').parent().hide(); $('#q11_6_3').parent().hide(); $('#q11_6_4').parent().hide(); $('#q11_6_5').parent().hide(); } }); 

The first part of the "if condition" works, however, when I cleared all the texts in q11_6_other, these switches will not hide. I think the else section is not working, but not sure how to get around it.

Thanks so much with your help !!!

+4
source share
4 answers

Place the other2text variable inside the event handler function:

 $('#q11_6_other').keypress(function(){ var other2text = $('#q11_6_other').val().length; 

In addition, I suggest using keyup instead of keypress . If you do this, you need to change other2text>=0 to other2text>0

+1
source

Your other2text variable is currently populated once on page load. You want it to run every time you press a button, so put this variable inside the function:

 $('#q11_6_other').keypress(function() { var other2text = $('#q11_6_other').val().length; ... 
0
source

Put the other2text variable inside the event handler

 $('#q11_6_other').keypress(function() { var other2text = $('#q11_6_other').val().length; 
0
source

That should do the trick

 $('#q11_6_other').keypress(function() { var other2text = $('#q11_6_other').val().length; 
0
source

Source: https://habr.com/ru/post/1380694/


All Articles