jquery - 如何过滤选择了空白或无值选项的任何选择字段的表单提交?

标签 jquery forms

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

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

提交功能的第二行不起作用。我尝试了几种组合,但不知道如何实现这一目标。谁能告诉我我做错了什么?

最佳答案

你可以试试这个

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

<强> Check Fiddle

Another One

关于jquery - 如何过滤选择了空白或无值选项的任何选择字段的表单提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149664/

相关文章:

jquery - 使用 jQuery 隐藏然后显示 div

c# - 使用 html 敏捷包解析表单操作并输入名称和值

c# - 多形式项目的录入方法是什么?

python - 当顺序无关紧要时,为 Web 构建适当的 SQL 查询

jQuery 单击验证而不提交

jquery - 在 JQuery 中引用类的当前对象

django - 在 Django 中发送动态 AJAX URL

javascript - Codeigniter jquery 在 AJAX 文件上传中不起作用

javascript - 使用 jQuery 将子元素向上移动一级

php - 根据表单中的行数将项目添加到购物车