Reputation: 167
I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Upvotes: 1
Views: 8211
Reputation: 337627
Firstly I'm assuming that the missing $
is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required
attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit
event of the form
, not the click
of the button
and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required
attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Upvotes: 2
Reputation: 66
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />
Upvotes: 0
Reputation: 29
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
Upvotes: 0