POST方法即使if条件失败也能工作


POST method working even the if condition fails

我有一个表单元素,里面有一些内容,如下所示。

<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>

和以下jQuery代码。

$("#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.
    }
});

这个else-if阶梯的最后一个else块包含了向insertserverdata.php提交数据的代码。我的意图是只有在两个文本字段填充了一些数据时才重定向到insertserverdata.php。但是当我点击提交按钮的文本字段内没有文本,jquery的if块将工作得很好,之后它会重定向到insertserverdata.php页面,但我不希望这样。我需要找什么零钱来填满呢?朋友们,请帮帮我。

尝试在每次无效检查时返回false,例如

$("#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 
});

还有一件事,在你的html

将两个文本框的id改为'ip'和'port'

试试这个,

$("#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;
});

尝试下面的方法,如果两个错误消息都为空,则显示两个错误消息,然后返回true,而不是显示其中一个错误消息。

$("#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.
    }
});
相关文章: