Jquery selector to find out count of non empty inputs

半腔热情 提交于 2019-12-21 07:55:01

问题


I have the below 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?


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/21410484/jquery-selector-to-find-out-count-of-non-empty-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!