Reputation: 1
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!");
}
})
});
Upvotes: 0
Views: 192
Reputation: 161
$("#frm").submit(function(e) {
e.preventDefault();
if ($("#txt").val().length < 6) {
$("#text-adder").text("Error");
} else {
$("#text-adder").text("Matched!");
}
})
Upvotes: 2
Reputation: 50291
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>
Upvotes: 1
Reputation: 30739
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!");
}
})
});
Upvotes: 0