Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reset value of multiple (but not all) form fields with jQuery in one line

Is it possible to reset multiple form fields in one line, or one hit, with jQuery. Note: I don't want to reset all form fields, only a specified whitelist (as below):

// reset some form fields                       
$('#address11').val('');
$('#address21').val('');
$('#town1').val('');
$('#county1').val('');
$('#postcode1').val('');
like image 720
crmpicco Avatar asked Nov 29 '22 08:11

crmpicco


2 Answers

It is better to use a class so you do not have to maintain a long list of ids.

HTML

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

JavaScript

$(".resetThis").val("");
like image 105
epascarello Avatar answered Dec 10 '22 21:12

epascarello


jQuery (and CSS) selector strings can contain multiple selectors using a comma as a delimiter for sub-selectors:

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

I'd argue that this is faster than using a class (ID look-ups should perform in essentially constant time, whereas a class look-up will have to visit every DOM node), but perhaps less maintainable if you're going to want to change which elements get reset.

like image 25
Cecchi Avatar answered Dec 10 '22 21:12

Cecchi