Reputation: 375
I'm new to Jquery and I seem to have come across a annoying problem.
How do I make the validation work only when a person hits submit?
Would I have to say -- if submit == true run function ?
<script>
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
</script>
Upvotes: 0
Views: 38
Reputation: 2343
Alert errors, flag if any, if there is flag - prevent submission form:
$('#add_film').submit(function(e) {
var err=0;
// No value for movie_title
if ($('#movie_title').val() == "" ) {
alert ("No Film");
err = 1;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert ("No actor");
err = 1;
}
// No value for rating
if ($('#rating').val() == null) {
alert ("No Rating");
err = 1;
}
//No value for review
if ($('#review').val() == "") {
alert ("No review");
err = 1;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if(err == 1){
e.preventDefault();
}
});
Upvotes: 0
Reputation: 193301
You should validate your form on form submit
event:
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
By the way, do not be tempted to bind validation to click event on the button, this is incorrect. Form elements have submit event for this purpose. Also make sure you prevent default behavior of the form in case of errors.
Upvotes: 1
Reputation: 6904
Move your code to click event of your button like this -
$(document).ready(function(){
$("#submit").on('click',function(){
// No value for movie_title
if ($('#movie_title').val() == "" ) {
alert ("No Film");
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert ("No actor");
}
// No value for rating
if ($('#rating').val() == null) {
alert ("No Rating");
}
//No value for review
if ($('#review').val() == "") {
alert ("No review");
}
});
// Focus on first form field.
$("input:text:visible:first").focus();
});
Upvotes: 1
Reputation: 8612
Remove it from .ready(), add it to onclick, on submit button. You might want to keep some of it on the .ready()... like focus on first element part.
Upvotes: 2