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>
>Solution :
You’re binding your event handlers in the wrong sequence and not checking it when you need to. Try this way:
var check = false;
$("#personal_deliver_same").on("click", function() {
check = $("#personal_deliver_same").is(':checked');
});
$("#input-payment-postcode").keyup(function() {
if (check && $("#input-payment-postcode").val().length > 5) {
console.log("in2");
}
});
<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>