I want to validate a value only when a checkbox is checked. I am able to get the validation running but if the checkbox is unchecked, the validation still runs.
Here is my code:
$("#personal_deliver_same").on("click", function(){
var check = $("#personal_deliver_same").is(':checked');
if(check){
$("#input-payment-postcode").keyup(function (){
if($("#input-payment-postcode").val().length > 5) {
alert("in2");
}
});
}
else{
alert("out2");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="control-label" for="input-payment-postcode">Post Code</label>
<input type="text" name="personal_details[postcode]" value="" placeholder="" id="input-payment-postcode" class="formcontrol">
<br>
<input type="checkbox" id="personal_deliver_same" name="personal_details[shipping_address]" value="1" />
<label>My Checkbox</label>
3
Answers
I think this will be what you want.
input
event instead of justclick
. Now when the value changes the event will occurinput
event of the text box for changes. If a change happens and the box is checked it will show you the outputYou’re binding your event handlers in the wrong sequence and not checking it when you need to. Try this way: