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

4

5

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('');
Imes answered 25/10, 2012 at 14:27 Comment(1)
Not sure why your question was downvoted... +1Allisan
A
8

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.

Allisan answered 25/10, 2012 at 14:28 Comment(2)
.class is faster :)Quite
Interesting, thanks for that. I assume parsing the selector string is what takes longer.Allisan
M
12

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("");
Monad answered 25/10, 2012 at 14:29 Comment(0)
A
8

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.

Allisan answered 25/10, 2012 at 14:28 Comment(2)
.class is faster :)Quite
Interesting, thanks for that. I assume parsing the selector string is what takes longer.Allisan
M
6

If you have a lot of fields i'd label the ones you want to ignore with a class to minimise code:

$('#myForm input:not(.ignore)').val('');
Macedo answered 25/10, 2012 at 14:33 Comment(0)
H
0

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

Hacienda answered 2/11, 2017 at 7:23 Comment(1)
This is the same as @Macedo 's answerImes

© 2022 - 2024 — McMap. All rights reserved.