简体   繁体   中英

jQuery value attribute selector not returning correct number of elements

I have a programme that generates a count after the key is up. JQuery Code:

$('.today').keyup(function() {
    var Presents = $('input[value="/"]:visible');
    $("#counter").html( "Present: " + Presents.length );
});

HTML:

<input type="text" id="1" name="1" class="today" value="/">
<input type="text" id="2" name="2" class="today" value="/">
<input type="text" id="3" name="3" class="today" value="/">
<p id="counter"></p>

The counter tag will display 3 after first key up. When i change the value in the text boxes the value does not change in the counter box. EG when i chance the value of text box 3 to x the

tag should now contain the number 2. Currently this does not change.

You are using an attribute selector, but when you change the input value, it won't change the attribute; just the property. You can use filter() to get what you need:

$('.today').keyup(function() {
    var Presents = $('input:visible').filter(function(){
      return this.value == "/";  
    });
    $("#counter").html( "Present: " + Presents.length );
});

JSFiddle

If you needed to update the attribute itself, you can do simply by adding the following to the top of your event handler:

$(this).attr('value',this.value);

JSFiddle

But that seems pretty messy to me. Also, I believe filter() will be faster than an attribute selector anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM