Reputation: 193
I am trying to make some simple validation in bootstrap and jquery Here is JS
$(document).ready(function() {
$("form").submit(function() {
if (($('input[name^=password]').val()) != password) {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
}
});
});
The problem is that form just continues?
Her is working bootply http://www.bootply.com/7Tvg4nhuG4
EDITED
I have made something like this, but i am not sure is it ok to have two IF
$(document).ready(function() {
$("form").submit(function() {
if ((($('input[name^=password]').val()) != password) || (($('input[name^=username]').val()) != username)) {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
return false;
}
if ((($('input[name^=password]').val()) != "") || (($('input[name^=username]').val()) != "")) {
return false;
}
else {
// do something
}
});
});
Upvotes: 1
Views: 65
Reputation: 14308
There are a couple of ways to do this. Your submit method can return false, or you can pass in the event as a parameter and call preventDefault to stop the default action (submit).
Return False
$(document).ready(function() {
$("form").submit(function() {
if (($('input[name^=password]').val()) != password) {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
return false;
}
});
});
PreventDefault
$(document).ready(function() {
$("form").submit(function(ev) {
if (($('input[name^=password]').val()) != password) {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
ev.preventDefault();
}
});
});
With that said, I would strongly recommend using a framework for form validation as it makes your code a lot more modular and maintainable. My personal preference is jQuery Validate which has been around for a long time and works very well, but there are many others are out there (eg. Parsley).
Upvotes: 2
Reputation: 61055
You haven't told the form to not submit, so it doesn't not submit. :-)
if (($('input[name^=password]').val()) != password) {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
return false; // this halts form submission
}
Upvotes: 2
Reputation: 12305
Fixed:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
if (($('input[name^=password]').val()) != "password") {
msg = 'Incorrect username or password';
$(".modal-body").text(msg);
$('#myModal').modal('show');
}
else
{
$(this).submit();
}
});
});
PS: I also change password
to "password"
to avoid undefined var error.
Upvotes: 1