2017-03-17 48 views
1

我有下面的代码将重置字段。我可以使用多个prop()在JQuery中的不同字段..?

$('#email').find('input,textarea').val(''); 
$('#email').find('input[type=checkbox]').prop('checked', false);    
$('#email').find('select option:eq(0)').prop('selected', true); 

我的问题是,我可以使上述代码类似于下面的代码。它是否有效..?

$('#email').find('input,textarea,input[type=checkbox],select option:eq(0)').val('').prop('checked', false).prop('selected', true); 
+0

不真的,因为'input'和'textarea'没有'checked'或'selected'属性。然而,假设这是表单的初始状态,你可以做'$('form')[0] .reset();' –

+0

#hat这是'$('#email')'它是一个div一个表单元素? –

+0

这是一个模态ID @SamuelJMathew –

回答

0

从技术上讲,你可以做到这一点。
因此,您将拥有一个带有checkedselected属性的textarea。

是的,它会工作。
是的,它不应该有任何不良影响。
但是,它听起来不太好。

此外,你的第二种方法绝对不会提高代码的可读性。

function display(propName) { 
 
    console.log("checkbox." + propName + " = " + $("#checkbox").prop(propName)); 
 
    console.log("text." + propName + " = " + $("#text").prop(propName)); 
 
    console.log("textarea." + propName + " = " + $("#textarea").prop(propName)); 
 
} 
 

 
display("checked"); 
 

 
$("input, textarea").prop("checked", true); 
 

 
display("checked");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input type="checkbox" id="checkbox"/> 
 
<input type="text" id="text"/> 
 
<textarea id="textarea"></textarea>

0

按我的实验,在这里,我得出一个结论,你可以使用重置下面的代码形式元素的DIV中: -

function reset() { 
 
    $(':input', '#email') 
 
    .not(':button, :submit, :reset, :hidden') 
 
    .each(function(i, e) { 
 
     $(e).val($(e).attr('value') || '') 
 
     .prop('checked', false) 
 
     .prop('selected', false) 
 
    }) 
 

 
    $('option[selected]', this).prop('selected', true) 
 
    $('input[checked]', this).prop('checked', true) 
 
    $('textarea', this).each(function(i, e) { 
 
    $(e).val($(e).html()) 
 
    }) 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="email"> 
 
    <input type="checkbox" id="checkbox" /> 
 
    <input type="text" id="text" /> 
 
    <textarea></textarea> 
 
    <select> 
 
    <option></option> 
 
    <option value="TRUE">TRUE</option> 
 
    </select> 
 
    <buttion onclick="reset()">Reset</button> 
 
</div>

相关问题