此表单总是提交,从不javascript停止错误。有什么问题?
提前感谢;)
我把onsubmit返回valida(this)....并且javascript代码似乎很好
<form name="formulario" id="formulario" method="POST" action="<%=request.getContextPath()%>/altaanuncio" onSubmit="return valida(this)">
function valida(f) {
if (f.marca.selectedIndex==0){
$('#errores').html('Seleccione la marca.');
f.marca.focus();
return false;
}
else if(f.garantia.value == ""){
$('#errores').html('Introduzca meses de garantía');
f.garantia.focus();
return false;
}
else if(f.pvpofertado.value == ""){
$('#errores').html('Introduzca el precio del coche');
f.pvpofertado.focus();
return false;
}
return true;
}
答案 0 :(得分:1)
你显然使用jQuery所以一直使用jQuery
可在此处找到验证插件:http://zoomzum.com/useful-jquery-form-validation/
并在此处发帖:http://api.jquery.com/jQuery.post/
<html>
<head>
<script type="text/javascript" src="jquery.latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#formulario").bind("submit",function(e) {
var f = this; // or $(this) but then you need to test .val() and use find() or children
if (f.marca.selectedIndex==0){
$('#errores').html('Seleccione la marca.');
f.marca.focus();
e.preventDefault();
}
.
.
.
.
}
$.post($(this).attr('action'),$(this).serialize(),
success: function( response ) {
console.log( response );
}
});
e.preventDefault(); // cancel the actual submit
});
});
</script>
</head>
<body>
<form name="formulario" id="formulario" method="POST" action="<%=request.getContextPath()%>/altaanuncio">
答案 1 :(得分:1)
我认为你试图在普通JS元素上调用 jQuery函数。试试这个:
// When the DOM is ready:
$(document).ready(function() {
// Attach submit event listener to form (== onSubmit)
$('#formulario').submit(function(event) {
// Get the jQuery object for the 'marca' field:
var marca = event.target.children('#marca');
if (marca.attr('selectedIndex') === 0) {
$('#errores').text('Seleccione la marca.');
marca.focus(); // <--this now works because it's a jQuery object.
event.preventDefault(); // instead of return false;
}
});
});
<form id="formulario" />