2012-10-31 60 views
1

我有形式标记像...如何筛选任何选择字段的表单提交,其中选择了空白或无值的选项?

<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 
    }); 
}); 

虽然提交函数的第二行不起作用。我尝试过几种组合,但无法弄清楚如何实现这一点。任何人都可以启发我,我做错了什么?

+0

逻辑将禁用每个选项,其值为'value =“”'无论是否选择了带值的选项 – charlietfl

回答

2

你可以试试这个

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

OR

$(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(); 
});​ 

Check Fiddle

Another One

+0

需要删除生产代码或表单中的e.preventDefault()永远不会提交。在页面加载时触发代码提交? – charlietfl

0
jQuery("#cart").submit(function(e) { 
    jQuery(this).find(':input').prop('disabled',function(){/* ':input will find select and input tags*/ 
     return $(this).val() ==''; 
    }); 
}); 

返回true在提交处理多余的。初始代码的另一个问题是selectinput元素不是窗体的子项。 children是直接后代

相关问题