循环遍历禁用控件的表单

Looping though form for disabled controls

我有一个带有输入、select、单选按钮等的表单,我想在其中检查具有属性 [disabled=disabled]

的控件 ID

我正在尝试一次将 class 应用于所有项目,并计划获得所有禁用控件以逗号分隔的输出。我的做法正确吗?

<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, ....'

使用 :disabled pseudo selector.

$("input:disabled").each(function(){
    var testdata = $(this).data('disabled');
});

你最好使用 pseudo,:input 会找到所有的输入元素、文本区域、复选框等

$(":input:disabled").each(function(){
    var testdata = $(this).data('disabled');
});

检索禁用元素的 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>

参考文献: