Reset value of several (but not all) form fields with jQuery in one line

Is it possible to use reset multiple form fields on the same line or one hit using jQuery. Note. I do not want to reset all form fields, only the specified whitelist (as shown below):

// reset some form fields $('#address11').val(''); $('#address21').val(''); $('#town1').val(''); $('#county1').val(''); $('#postcode1').val(''); 
+4
source share
4 answers
Selection lines

jQuery (and CSS) can contain several selectors that use a comma as a separator for subselectors:

 $('#address11, #address21, #town1, #county1, #postcode1').val(''); 

I would say that this is faster than using the class (the ID search should be performed mainly by constant time, while the class search will have to visit every DOM node), but maybe less service if you want to change which elements get reset.

+7
source

It is better to use a class, so you do not need to maintain a long list of identifiers.

HTML

 <input type="text" class="resetThis" id="address11" /> <input type="text" class="resetThis" id="address21" /> 

Javascript

 $(".resetThis").val(""); 
+10
source

If you have many fields, I would name those that you want to ignore with the class in order to minimize code:

 $('#myForm input:not(.ignore)').val(''); 
+6
source

You can use $('#Form_name select:not(.fixed)').val('');

0
source

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


All Articles