Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jquery – validate textbox based on checkbox

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading