简体   繁体   中英

If else statement is not working in jquery

I am trying to make a form validator that requires at least 6 characters in the input text field. It's supposed to show error if the length is less than 6 and Matched! if its more than 6. But, it's showing error no matter how long the character is.

$(function() {
  let texts = $("#txt").val();
  let password = $("#pass").val();

  $("#frm").submit(function(e) {
    if (texts.length < 6) {
      $("#text-adder").text("Error");
      e.preventDefault();
    } else {
      $("#text-adder").text("Matched!");
    }
  })
});
$("#frm").submit(function(e) {
  e.preventDefault();   
  if ($("#txt").val().length < 6) {
    $("#text-adder").text("Error");

  } else {
    $("#text-adder").text("Matched!");
  }
})

Get the text & password value inside the submit function. This is because the on submit it needed to check the value. But if you get it outside the submit function that will not get the updated value on submit

 $("#frm").submit(function(e) { e.preventDefault(); let texts = $("#txt").val(); let password = $("#pass").val(); if (texts.length < 6) { $("#text-adder").text("Error"); } else { $("#text-adder").text("Matched!"); } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

You need to actually get the value of the #txt field inside the submit function so that the value is updated with the latest value:

$(function() {
  $("#frm").submit(function(e) {
    let texts = $("#txt").val();
    let password = $("#pass").val();
    if(texts.length < 6) {
        $("#text-adder").text("Error");
        e.preventDefault();
    }
    else {
        $("#text-adder").text("Matched!");
    }
  })
});

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