2

我有表单标记,如......

<form id='cart' action="/cart/add" method="post">
    <div id="product-variants">
        <div class="selector-wrapper clearfix">
        <select class="product-select" name='id[]'>
            <option value="">&nbsp;---</option>
            <option value="a">Option A</option>
            <option value="b">Option B</option>
            <option value="c">Option C</option>
        </select>
        <select class="product-select" name='id[]'>
            <option value="">&nbsp;---</option>
            <option value="a">Option A</option>
            <option value="b">Option B</option>
            <option value="c">Option C</option>
        </select>
        </div>
    </div>
</form>

我正在尝试编写一个例程来过滤掉(禁用)任何值为空白的选择输入,这样它就不会被发送到我无法控制的后端。这是我根据对我在这里找到的其他问题的回答得出的结论。

jQuery(function(){
  jQuery("#cart").submit(function(){
    $(this).children(':input[value=""]').attr("disabled", "disabled");
    $(this).children('select option[value=""]').parent().attr("disabled","disabled");
    return true; // ensure form still submits
  });
});

提交功能的第二行虽然不起作用。我已经尝试了几种组合,但无法弄清楚如何实现这一点。谁能告诉我我做错了什么?

4

2 回答 2

4

你可以试试这个

$(this).find('select').filter(function() {
      return this.value === ''
 }).prop("disabled", true);

或者

$(this).find('select').each(function() {
     if (this.value == '') {
        $(this).prop("disabled", true);
     }
});

完整代码

jQuery(function() {
    jQuery("#cart").submit(function(e) {
       // e.preventDefault();
        $(this).find('select').each(function() {
            if (this.value == '') {
                $(this).prop("disabled", true);
            }
        });
    });

    jQuery("#cart").submit();
});​

检查小提琴

另一个

于 2012-10-31T00:44:35.437 回答
0
jQuery("#cart").submit(function(e) {
  jQuery(this).find(':input').prop('disabled',function(){/* ':input will find select and input tags*/
        return $(this).val() =='';
   });
});

在提交处理程序中返回 true 是多余的。select初始代码的另一个问题是input元素不是表单的子元素。children是直系后代

于 2012-10-31T00:54:35.783 回答