[英]How to reset a particular form field using jQuery
我想知道如何使用jQuery重置特定的表單字段。
我正在使用以下功能:
function resetForm(id) {
$('#'+id).each(function(){
this.reset();
});
}
但它正在重置所有字段。 有沒有辦法使用jQuery或JavaScript重置特定字段? 我想只重置一個特定的字段。
function resetForm(id) {
$('#' + id).val(function() {
return this.defaultValue;
});
}
不使用id的示例:
reset()
方法通過設計影響整個表單,只重置特定的input
元素,假設element after each
輸入element after each
一個Reset前一個輸入element after each
:
$('button.reset').click(
function(){
var input = $(this).prev('input:first');
input.val(''); // assuming you want it reset to an empty state;
});
要將input
重置為其原始狀態,首先我建議將原始值存儲在data-*
屬性中以進行重新收集:
$('input').each(
function(){
$(this).attr('data-originalValue',$(this).val());
});
$('button.reset').click(
function(){
var input = $(this).prev('input:first');
input.val(input.attr('data-originalValue'));
});
給定HTML類似於以下(其中input
元素組合在一起):
<form action="#" method="post">
<fieldset>
<input value="something" />
<button class="reset">Reset the input</button>
</fieldset>
<fieldset>
<input type="checkbox" name="two" />
<input type="checkbox" name="two" checked />
<input type="checkbox" name="two" />
<button class="reset">Reset the input</button>
</fieldset>
<fieldset>
<input type="radio" name="three" checked />
<input type="radio" name="three" />
<button class="reset">Reset the input</button>
</fieldset>
</form>
以下jQuery會將input
元素重置為其頁面加載狀態:
$('button.reset').click(
function () {
$(this).prevAll('input').val(function(){
switch (this.type){
case 'text':
return this.defaultValue;
case 'checkbox':
case 'radio':
this.checked = this.defaultChecked;
}
});
});
JS小提琴演示 。
參考文獻:
我的方法是考慮三種情況:基於自由輸入的字段,基於檢查的字段和基於選擇的字段。
$(set_of_fields).each(function() {
// Don't bother checking the field type, just check if property exists
// and set it
if (typeof(this.defaultChecked) !== "undefined")
this.checked = this.defaultChecked;
if (typeof(this.defaultValue) !== "undefined")
this.value = this.defaultValue;
// Try to find an option with selected attribute (not property!)
var defaultOption = $(this).find('option[selected]');
// and fallback to the first option
if (defaultOption.length === 0)
defaultOption = $(this).find('option:first');
// if no option was found, then it was not a select
if (defaultOption.length > 0)
this.value = defaultOption.attr('value');
});
編輯:我剛注意到這不適用於<select multiple>
字段。
你可以這樣做(如果你打算使用reset() javascript方法):
function resetForm(id) {
document.getElementById(id).reset();
}
不需要jQuery,因為“reset”方法是一種標准的javascript方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.