jquery form submit not working
in some reason if I use this code it sends the form in normal way not with jquery? What could be the problem? thanks
<script>
$(document).ready(function() {
$("form#formi").submit(function() {
$(":text, textarea").each(function() {
if ($(this).val() === "")开发者_运维百科 {
$('p#error').fadeIn(1000);
var tyhjia = true;
}
});
if (tyhjia == true) {
// tyhjia on , joten ei jatketa
} else {
// we want to store the values from the form input box, then send via ajax below
var fname = $('#name').attr('value');
var lname = $('#email').attr('value');
$.ajax({
type: "POST",
url: "laheta-viesti",
data: "name=" + fname + "& email=" + lname,
success: function() {
$('form#formi').hide();
$('p#valmista').fadeIn(1000);
}
});
}
return false;
});
});
</script>
Errors in your javascript are the common cause for this behavior. For example you have defined the tyhjia
variable inside the anonymous callback and try to use it outside. I have tried to clean your code a little:
<script type="text/javascript">
$(document).ready(function() {
$('form#formi').submit(function() {
var tyhjia = false;
$(':text, textarea').each(function() {
if($(this).val() === '') {
$('p#error').fadeIn(1000);
tyhjia = true;
}
});
if (tyhjia == true) {
// tyhjia on , joten ei jatketa
} else {
// we want to store the values from the form input box, then send via ajax below
var fname = $('#name').val();
var lname = $('#email').val();
$.ajax({
type: 'POST',
url: 'laheta-viesti',
data: { name: fname, email: lname },
success: function() {
$('form#formi').hide();
$('p#valmista').fadeIn(1000);
}
});
}
return false;
});
});
</script>
Of course there could be some other errors left. Use FireBug or Chrome Developer Tool and inspect the console for any possible errors reported.
And by the way for doing validation, which is what apparently you are trying to do here, I would very strongly recommend you the jquery validate plugin.
if you want the jquery behavior to replace the default behavior completely, you must explicitly tell it to not do the default behavior like this:
$(document).ready(function(){
$("form#formi").submit(function(e) {
e.preventDefault();
notice that two lines of code changed - you must get "e" which is a common abbreviation for "event" from the function as a parameter, then tell it not to perform the default behavior.
精彩评论