ngplayground
ngplayground

Reputation: 21667

jQuery multiple inputs and checking length

I'm trying to combine 4 input fields into a jQuery function so that it checks each input as its keyup'd and when all the boxes reaches a length of 4 then the list item changes to acknowledge all fields are full

HTML

<div class="cardNumber">
    <input type="text" value="" maxlength="4" name="ccn1" id="ccn1">
    <input type="text" value="" maxlength="4" name="ccn2" id="ccn2">
    <input type="text" value="" maxlength="4" name="ccn3" id="ccn3">
    <input type="text" value="" maxlength="4" name="ccn4" id="ccn4">
</div>

<ul>
    <li class="checkNumber">Card Number</li>
</ul>

jQuery

$(".cardNumber input[name=ccn1], .cardNumber input[name=ccn2], .cardNumber input[name=ccn3], .cardNumber input[name=ccn4]").keyup(function() {
    $(".cardNumber input[name=ccn1], .cardNumber input[name=ccn2], .cardNumber input[name=ccn3], .cardNumber input[name=ccn4]").each(function() {
        if ($(".cardNumber input[name=ccn1], .cardNumber input[name=ccn2], .cardNumber input[name=ccn3], .cardNumber input[name=ccn4]").length >= '4') {
            $("li.checkNumber").addClass("checked");
        }
    });
});

Demo: http://jsfiddle.net/fz4wF/

Upvotes: 0

Views: 2198

Answers (4)

thecodeparadox
thecodeparadox

Reputation: 87073

$(':input[name^=ccn]').keyup(function() {
    var check = $(':input[name^=ccn]').filter(function() {
        return $.trim(this.value).length < 4;
    }).length === 0;

    $("li.checkNumber").toggleClass("checked",check);
});

DEMO

Upvotes: 6

loler
loler

Reputation: 2587

i think the easiest way is this: http://jsfiddle.net/fz4wF/28/ not the best.

Upvotes: 0

aquinas
aquinas

Reputation: 23796

Something like this:

http://jsfiddle.net/fz4wF/19/

$(".cardNumber input").keyup(function(){    
    var allfilled = true;
    $(".cardNumber input").each(function() {
        if($(this).val().length < 4) {
            allfilled =false;
            return false;
        }
    });  

    $("li.checkNumber").toggleClass("checked",allfilled);    
});​

Upvotes: 4

Samson
Samson

Reputation: 2821

I believe this is what you need.

Upvotes: 0

Related Questions