简体   繁体   中英

jQuery form validation not resulting in border outline?

Hi please see my code as I am not sure what I did wrong. The code should run in browser as highlight red if input value does not exist and highlight green if value of input exist. please help me. I think it is because my input.val() is undefined, however the borders do not show up regardless.

 $(document).ready(function(){ $('.form-control').on('input', function(){ //sets var input as the form-control var input = $(this); //assigns is_name as the value of the input var is_name = input.val(); if(is_name) { input.removeClass(".invalid").addClass(".valid"); } else { input.removeClass(".valid").addClass(".invalid"); } }); }); 
 input.invalid { border: 2px solid red; } input.valid { border: 2px solid green; } 
 <form role="form"> <br /> <span class="error">This field is required</span> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-tag" ></i></span> <input type="text" class="form-control" placeholder="Your Username " /> </div> <span class="error">This field is required</span> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-lock" ></i></span> <input type="password" class="form-control" placeholder="Your Password" /> </div> <div class="form-group"> <label class="checkbox-inline"> <input type="checkbox" /> Remember me </label> <span class="pull-right"> <a href="#" >Forget password ? </a> </span> </div> <button class="btn btn-danger" type="submit" id="signin">Sign In</button> <hr /> Not register ? <a href="register.html" >click here </a> </form> </div> 

After updated /modified your code, it is working now. You can find in FIDDLE

JS code

$('#signin').click(function(){
  //sets var input as the form-control
  var input = $('.form-control');
  //assigns is_name as the value of the input

  var is_name = input.val();        
  if(is_name) {
    input.removeClass("invalid").addClass("valid");
  } else {
    input.removeClass("valid").addClass("invalid");
  }
});

CSS

.invalid {
    border: 2px solid red;
}
.valid {
    border: 2px solid green;
}

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