Reputation: 6318
I'm attempting a simple if/else that worked in a previous project. But I'm having trouble making it work in a new project.
I have trimmed it down to the simplest version here.
HTML:
<form name="mainForm" action="formProc.php" method="get" id="mainForm" onSubmit="return allChecks();" >
<input type="text" name="name" id="name"/>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
//formVars
var name = $('#name');
function allChecks(){
if(name.val()==""){
alert("lopan");
return false;
}
if(name.val()===""){
alert("lopan");
return false;
}
if(name.val()== null){
alert("lopan");
return false;
}
return false;
}
});
</script>
I'm trying to force a "false" on the form but it still goes to the next page.
I also created another button in the form with type="button", declare it and used:
var btn= $('#clearF');
btn.click(allChecks);
This works, but I'm not sure why.
In troubleshooting, I noticed it went through to the next page. So I started trying to prevent it from going to the next page by adding validation to the fields. The goal is to block it from going to the next page unless valid.
Upvotes: 2
Views: 155
Reputation: 42182
Had something like that a while ago, productive code that suddenly changed behavior with submitting. What i now do is in stead of your (fairly normal) code.
<form name="mainForm" action="formProc.php" method="get" id="mainForm" >
<input type="text" name="name" id="name"/>
var btn= $('#clearF');
btn.click(allChecks);
$(document).ready( function(){
//formVars
var name = $('#name');
function allChecks(){
if(name.val()==""){
alert("lopan");
return false;
}else{
mainForm.submit();
}
return false;
}
});
</script>
Upvotes: 0
Reputation: 144669
you can handle submit event this way:
$(document).ready( function(){
//formVars
var name = $('#name');
$("#mainForm").submit( function() {
if ( name.val() === "" ) {
alert("lopan");
return false;
}
else {
return true;
}
});
});
Upvotes: 0
Reputation: 119837
instead of onsubmit
on the markup, why not use jQuery in creating a handler?
$(document).ready(function(){
$('#mainForm').on('submit',function(){
//whatever you want to do on submit
});
});
Upvotes: 0
Reputation: 48793
allChecks
is not 'visible' for your markup. It is inside of $(document).ready()
handler. To make it 'visible' just declare it like this:
window.allChecks=function(){
Upvotes: 3