简体   繁体   中英

Validate form input text while user write

I would like to validate my form during the writing by user. Now I'm using this javascript:

$(document).ready(function (){
    validate();
    $('#initialKm, #carChassis').change(validate);
});

function validate(){
    if ($('#initialKm').val().length   >   0   &&
            $('#carChassis').val().length  >   0 ){
        $("#saveCarButton").prop("disabled", false);
    }
    else {
        $("#saveCarButton").prop("disabled", true);
    }
}

The only problem is that to execute the validation, after the user has filled the input tag, he has to click elsewhere to activate the button. Is it possible to activate while user fill the field?Thanks

Use $('#initialKm, #carChassis').keyup(validate)

Change only fires after the input focus is lost.

Try using input event

 $(document).ready(function () { validate(); $("#initialKm, #carChassis").on("input", validate); }); function validate() { $("#saveCarButton") .prop("disabled", !$('#initialKm').val().length && !$('#carChassis').val().length); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="text" id="initialKm" /> <input type="text" id="carChassis" /><br> <button id="saveCarButton">click</button> 

$(document).ready(function () {
    $("#initialKm, #carChassis").keyup(validate);
});

function validate() {
  $("#saveCarButton")
  .prop("disabled", 
   !$('#initialKm').val().length 
    && !$('#carChassis').val().length);
}

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