Man*_*gir 14 javascript jquery
我想知道如何使用jQuery重置特定的表单字段.
我正在使用以下功能:
function resetForm(id) {
$('#'+id).each(function(){
this.reset();
});
}
Run Code Online (Sandbox Code Playgroud)
但它正在重置所有字段.有没有办法使用jQuery或JavaScript重置特定字段?我想只重置一个特定的字段.
Esa*_*ija 19
function resetForm(id) {
$('#' + id).val(function() {
return this.defaultValue;
});
}
Run Code Online (Sandbox Code Playgroud)
不使用id的示例:
该reset()方法通过设计影响整个表单,仅重置特定input元素,假设存在重置先前输入输入element after each`:
$('button.reset').click(
function(){
var input = $(this).prev('input:first');
input.val(''); // assuming you want it reset to an empty state;
});
Run Code Online (Sandbox Code Playgroud)
要重置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'));
});
Run Code Online (Sandbox Code Playgroud)
给定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>
Run Code Online (Sandbox Code Playgroud)
以下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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
36823 次 |
| 最近记录: |