获取字段集中所有jquery输入的值

Get the value of all the jquery inputs within a fieldset

本文关键字:输入 jquery 字段 集中 获取      更新时间:2023-09-26

这是我在这里问的第一个问题。我有一个字段集里面有4个输入。我想验证的形式,如果至少2的4已完成。我可以用$("#communications input").val()得到第一个输入的值。

 <fieldset class="input-group-fieldset bigger-labels" id="communications">
    <div class="row">
        <div class="columns twelve">
            <div class="input-group" id="pref-mail-wrap">
                <label>Email Address</label>
                @Html.TextBoxFor(model => model.PrefferedEmail, new { @class = "contact-group" })
            </div>
        </div>
    </div>
    <div class="row">
        <div class="columns four">
            <div class="input-group" id="pref-phone-wrap">
                <label>Telephone No</label>
                @Html.TextBoxFor(model => model.PrefferedPhoneNo, new { @class = "contact-group" })

            </div>
        </div>
        <div class="columns four">
            <div class="input-group" id="pref-sms-wrap">
                <label>SMS No</label>
                @Html.TextBoxFor(model => model.PrefferedSmsNo, new { @class = "contact-group" })
            </div>
        </div>
    </div>
    <div class="" id="pref-address-wrap">
        <div class="row fixed-width">
            <div class="columns twelve">
                <div class="input-group2">
                    <label>Address </label>
                    @Html.TextBoxFor(model => model.PostalAddress)
                </div>
            </div>
        </div>

提前谢谢你,考斯塔斯。

如下所示使用.filter()

var $completedInputs = $("#communications input:text").filter(function() {
    //return the ones witn non-empty values
    return $.trim(this.value) != "";
});
if ($completedInputs.length >= 2) {
    //At least 2 inputs have been filled.   
}

$("#communications input:text")$("#communications :text") =>所有类型为text的输入

$("#communications input") =>所有输入

您应该为所有这些input元素设置name属性,然后将它们序列化并使用:

if($('#communications :input').serializeArray().length >=2)

'#communications input'就足够了

你可以使用jquery的each()选择器返回多于1个元素:

$("#communications input").each(function(){
   // $(this).val(); check here what you want.
})

试试这样做。

var count = 0;
$('#communications input').each(function(index, item) {
    if($(item).val()!=="") {
        count ++;
    }
    return count <= 2; // break; if more than 2 have values
    });
if(count >= 2) {
    //valid
}

阅读更多:https://api.jquery.com/each/

您可以使用filter()来检查有多少inputs被赋予了一个值。试试这个:

var validInputs = $("#communications input").filter(function() {
    return !$(this).val().trim() == '';
}).length;
if (validInputs < 2) {
    // form is invalid...
}

如果所有输入具有相同的格式并且验证相同尝试遍历fieldset

中的所有输入
$("#communications input").each(function(i,v){
});

否则,您应该分别验证4个输入