0

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!");
    }
  })
});
3
  • Add your HTML also Commented Dec 21, 2018 at 11:13
  • 3
    texts will always be the initial value, move let texts = $("#txt").val(); inside the event handler Commented Dec 21, 2018 at 11:14
  • You have to get the texts value when you submit the form. Commented Dec 21, 2018 at 11:15

3 Answers 3

2
$("#frm").submit(function(e) {
  e.preventDefault();   
  if ($("#txt").val().length < 6) {
    $("#text-adder").text("Error");

  } else {
    $("#text-adder").text("Matched!");
  }
})
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

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!");
    }
  })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.