neelmeg
neelmeg

Reputation: 2509

input field validation using jquery

I'm adding a class "valid" to an input field if it matches the email and password criteria. I want to enable a submit button if both the fields have a valid class once the class valid is added it stays there even if the entered input is erased completely.

To fix this I have to either remove the valid class or increment the counter when the field is not empty. I'm trying the second case where I'm checking if the class valid is present and also if the field is not empty. I'm not getting the desired effect with the code below:

<input type="email" name="email" placeholder="Email" class="email required valid" id="aim_Email">
<input type="password" name="password" id="aim_Password" placeholder="Password" class="newpassword password required aimError" style="">


$('.required').live('blur', function (value) {
  if ($(this).hasClass('valid') && $(this).val()) {
    count++;
    if (count > 1) {
      alert('event fired');
      $(".submit").removeClass("disabled");
      $(C.options.currentPage).find('input[type="submit"]').removeAttr("disabled");
      $('.passwordHint').hide();
    }
  }
});

Upvotes: 0

Views: 1392

Answers (3)

wirey00
wirey00

Reputation: 33661

Just check on each keyup event. And use toggleClass().. as it allows for a condition to be passed in.. so if true it adds class.. if false it removes class

$('.submit').prop('disabled',true); // <-- disable button on load
$('.required').keyup(function() { // <-- bind keyup to both required inputs
    $('.required').each(function(i, v) { // <-- loop through each required field
            $(v).toggleClass('valid',$(v).val().trim().length > 0); // <-- add class if it has text
    }); 
    $('.submit').prop('disabled', $('.valid').length != 2); // button disabled if there's not 2 valid fields
});​

http://jsfiddle.net/nxLeJ/3/

Upvotes: 0

Siwei Kang
Siwei Kang

Reputation: 186

You need to decrement the count once it is empty, you also need to limit the counts within the number of input fields. Check out this jsFiddle

Upvotes: 1

badunk
badunk

Reputation: 4350

The example is not complete as there is a reference to a C.options.currentPage and count is undefined.

With that said, I'm not sure what it is you're expecting, because it sorta works for me. Check the jsFiddle here. I've modified your code a bit.

Upvotes: 0

Related Questions