我有一个带输入,选择,单选按钮等的表单,我想用属性[disabled = disabled]检查控件ID
我正在尝试一次将类应用于所有项目,并计划使用逗号分隔所有禁用的控件来输出。我的方法是否正确?
<form id="saveForm">
<input type='text' name='firstname' id='firstname' disabled='disabled'>
<input type='text' name='lastname' id='lastname' disabled='disabled'>
etc.,
</form>
$("input[disabled]").each(function(){
var testdata = $(this).data('disabled');
});
我想要的是输出:
'#firstname,#lastname,....'
答案 0 :(得分:1)
$("input:disabled").each(function(){
var testdata = $(this).data('disabled');
});
答案 1 :(得分:1)
你最好使用伪,:input
会找到所有输入元素,textarea,复选框等。
$(":input:disabled").each(function(){
var testdata = $(this).data('disabled');
});
答案 2 :(得分:1)
要检索已禁用元素的id
的逗号分隔列表:
var idsOfDisabled = $('form [disabled]').map(function() {
return this.id;
}).get().join(',');
console.log(idsOfDisabled); // firstname,lastname,title
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="saveForm">
<input type='text' name='firstname' id='firstname' disabled='disabled' />
<input type='text' name='lastname' id='lastname' disabled='disabled' />
<select disabled="disabled" id="title">
<option>Mr</option>
<option>Mrs</option>
<option>Ms</option>
<option>Dr.</option>
</select>
</form>
如果需要#
字符,则:
var idsOfDisabled = $('form [disabled]').map(function() {
return '#' + this.id;
}).get().join(',');
console.log(idsOfDisabled); // #firstname,#lastname,#title
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="saveForm">
<input type='text' name='firstname' id='firstname' disabled='disabled' />
<input type='text' name='lastname' id='lastname' disabled='disabled' />
<select disabled="disabled" id="title">
<option>Mr</option>
<option>Mrs</option>
<option>Ms</option>
<option>Dr.</option>
</select>
</form>
或者,在纯JavaScript中仅使用本机DOM:
var idsOfDisabled = Array.prototype.map.call(document.querySelectorAll('form [disabled]'), function (disabledElem) {
return '#' + disabledElem.id;
}).join(',');
console.log(idsOfDisabled);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="saveForm">
<input type='text' name='firstname' id='firstname' disabled='disabled' />
<input type='text' name='lastname' id='lastname' disabled='disabled' />
<select disabled="disabled" id="title">
<option>Mr</option>
<option>Mrs</option>
<option>Ms</option>
<option>Dr.</option>
</select>
</form>
参考文献: