javascript 检查jQuery中是否至少填写了一个输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13416545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:42:45  来源:igfitidea点击:

Check if at least one input field is filled in jQuery

javascriptjqueryinput

提问by L.S

I have a jQuery script that checks if at least one input field contains text but it doesn't check my select option. Can anybody please help me to implement it?

我有一个 jQuery 脚本,用于检查是否至少有一个输入字段包含文本,但它不会检查我的选择选项。有人可以帮我实施它吗?

The script:

剧本:

$(function(){
    $("#myform").submit(function(){

        var valid=0;
        $(this).find('input[type=text]').each(function(){
            if($(this).val() != "") valid+=1;
        });

        if(valid){
            alert(valid + " inputs have been filled");
            return true;
        }
        else {
            alert("error: you must fill in at least one field");
            return false;
        }
    });
});

and the HTML for testing this:

以及用于测试的 HTML:

<form action="/echo/html" id="myform" method="post">
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>

<select name="something" id="something" type="text">
<option value=""></option>
<option value="one">Option one</option>
<option value="two">Option two</option>
<option value="three">Option three</option>
</select>

<input type="submit"/>
</form>?

回答by Sceletia

For one statement to grab both 'select' and 'input' elements, simply change your single jQuery selector to a multiple selector, like so:

对于同时获取 'select' 和 'input' 元素的语句,只需将您的单个 jQuery 选择器更改为多个选择器,如下所示:

$(this).find('input[type=text], select').each(function(){
            if($(this).val() != "") valid+=1;
        });