javascript Jquery选择器找出非空输入的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21410484/
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-27 20:52:05  来源:igfitidea点击:

Jquery selector to find out count of non empty inputs

javascriptjqueryknockout.js

提问by Bumble

I have the below HTML DOM

我有以下 HTML DOM

      <div id="container>
        <p data-bind="visible:ShowPostCode()">
    <label class="field-label" for="postcode">Postcode</label>
    <input id="txtPostCode" data-bind="value:PostCode, valueUpdate: &quot;afterkeydown&quot;" class="field-stretch" type="text">
    </p>

     <p data-bind="visible:ShowDateOfBirth()">
    <label class="field-label" for="dateofbirth">Date of birth</label>
    <input data-bind="value:DateOfBirth, valueUpdate: &quot;afterkeydown&quot;" class="field-stretch" type="text">
    </p>

             <p style="display: none;" data-bind="visible:ShowtelephoneNumber()">
    <label class="field-label" for="telephoneNumber">Telephone number</label>
    <input data-bind="value:DrivingLicenceNumber, valueUpdate: &quot;afterkeydown&quot;" class="field-stretch" type="text">
    </p>
   </div>

I would like to get the no of non-empty input boxes.

我想获得非空输入框的编号。

This is what i tried

这是我试过的

$('#container input[type="text"][value!=""]').length

or

或者

$('#container input[type="text"]').filter('input[value!=""]').length

even when i input some values it is always showing as zero . what is wrong with these selectors i tried and why it is not working?

即使我输入了一些值,它也总是显示为零。我试过的这些选择器有什么问题,为什么它不起作用?

回答by plalx

You can pass in a filter function rather than a selector:

您可以传入过滤器函数而不是选择器:

$('#container input[type="text"]').filter(function () {
    return !!this.value;
}).length;

回答by Anton

The attribute value will always be the default value so you must filter through the input boxes and check the value like this code below

属性值将始终是默认值,因此您必须过滤输入框并检查如下代码所示的值

$('#container input[type="text"]').filter(function () {
    return this.value.length > 0
}).length;

DEMO

演示