Reputation: 169
I hava a form element with some contents inside as given below.
<form action="insertserverdata.php" id="toPopup">
<table>
<tr>
<td>IP address:</td>
<td><input type="text" id="ip" /></td>
</tr>
<tr>
<td>Port:</td>
<td><input type="text" id="port" /></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
and the following jQuery code.
$("#toPopup").submit(function(event){
if($('#ip').val()=="") {
alert("IP field is Empty");
}else if($('#port').val()=="") {
alert("Port field is Empty");
}else {
//else code to be executed.
}
});
Here the last else block of this else-if ladder contains the code for posting data to insertserverdata.php. And my intention is to redirect to insertserverdata.php only if the two text fields are populated with some data. But when I click submit button the with no text inside text fields, the if blocks of jquery will works fine and after that it will redirect to insertserverdata.php page, but i dont want that.What change shall I need to full fill that?. Please help me friends.
Upvotes: 0
Views: 159
Reputation: 3160
Try the following which should show both error messages then returns true instead of showing one or the other error message if both are empty.
$("#toPopup").submit(function(event){
var errors = false;
if($.trim($('#ip').val())=="") {
alert("IP field is Empty");
errors = true;
}
if($.trim($('#port').val())=="") {
alert("Port field is Empty");
errors = true;
}
if(errors){
return false;
}else{
//else code to be executed.
}
});
Upvotes: 0
Reputation: 40639
Try this,
$("#toPopup").submit(function(event){
event.preventDefault();
if($('#ip').val()=="") {
alert("IP field is Empty");
}else if($('#port').val()=="") {
alert("Port field is Empty");
}else {
//else code to be executed.
return true;
}
return false;
});
Upvotes: 2
Reputation: 28763
Try to return false on each invalid check like
$("#toPopup").submit(function(event){
if($('#ip').val()=="") {
alert("IP field is Empty");
return false;
}else if($('#port').val()=="") {
alert("Port field is Empty");
return false;
}
//Do the stuff
});
And one more thing ,change the id's of two text boxes to 'ip' and 'port' at your html
Upvotes: 4