reset value of multiple (but not all) form fields

2019-06-24 09:44发布

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('');

4条回答
做自己的国王
2楼-- · 2019-06-24 10:32

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

查看更多
神经病院院长
3楼-- · 2019-06-24 10:35

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('');
查看更多
看我几分像从前
4楼-- · 2019-06-24 10:39

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-06-24 10:40

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("");
查看更多
登录 后发表回答