如何使用表单中的多个按钮解决验证问题

时间:2015-03-13 13:18:29

标签: javascript

我有一个表单,有一些用户可以填写的文本框。在表单底部我有两个按钮。一个用于取消,一个用于提交。如下例所示

<form action='bla.php' method='post'>
    <input type='text' name='someTextField1'>
    <input type='text' name='someTextField2'>
    <input type='text' name='someTextField3'>
    <input type='submit' name='submit'>
    <input type='submit' name='cancel'>
</form>

我有一个js函数可以检查字段中的数据,这些数据我曾用于两个按钮。因此,请参考以下表格中的js函数:

<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>

js函数如下所示:

function CheckFields() {
    var formname = "form";
    var x = document.forms[formname]["someTextField1"].value;
    var result = true;
    var text = "";
    if (x == null || x == "") {
        text += "Dont forget about the someTextField1.\n";
        result =  false;
    }

    if(!result)
        alert(text);
    return result;
}

现在我希望这个js函数只在使用submit而不是cancel按钮时运行。当我尝试将对函数的调用移动到如下所示的提交按钮时,它不起作用:

<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>

为什么呢?解决这个问题最聪明的方法是什么?我是否应该在表单中保留对CheckFields()的调用,并在脚本中检查单击了哪个按钮,或者我应该将该函数重新设置为使用某个按钮进行操作?有人有想法或榜样吗?

4 个答案:

答案 0 :(得分:2)

<input type='submit' name='cancel'>替换为<input type='button' name='cancel'>
您的版本实际上有两个提交按钮,两个都将提交表单。

答案 1 :(得分:1)

首先,如果您想在提交前使用javascript检查所有字段,则不需要在表单上提交按钮。

我认为最明智的做法如下:

您的表单(没有操作,提交按钮和方法。仅识别带有ID的每个组件):

<form id="formId">
    <input type='text' id="text1">
    <input type='text' id="text2">
    <input type='text' id="text3">
    <input type='button' id="accept">
    <input type='button' id="cancel">
</form>

你的javascript(你必须添加jQuery):

jQuery("#formId").on("click", "#accept", function(){  //listen the accept button click

    if(CheckFields()){ //here you check the fields and if they are correct
                       //then get all the input values and do the ajax call sending the data
        var text1 = jQuery("#text1").val();
        var text2 = jQuery("#text2").val();
        var text3 = jQuery("#text3").val();

        jQuery.ajax({
            url: "bla.php",
            method: "POST",
            data: {
                "someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
                "someTextField2":text2,
                "someTextField3":text3
            },
            success: function(){
                //here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
            }
        });
    }

});

jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button

 //here you can clean the form, etc
});

function CheckFields() {        //here I did a little change for validating, using jQuery.
    var x = jQuery("#text1").val();
    var result = true;
    var text = "";
    if (x == null || x == "") {
        text += "Dont forget about the someTextField1.\n";
        result =  false;
    }

    if(!result)
        alert(text);
    return result;
}

我希望它可以帮到你!

答案 2 :(得分:1)

观看此示例http://jsfiddle.net/355vw560/

<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
    <br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">

无论如何,使用jquery或事件监听器总是更好,而不是直接在dom中管理事件。

该函数没有用,因为它的范围是元素,如果你指定窗口作为你的函数工作的上下文。

答案 3 :(得分:0)

I handle it with this way , Hope it will help.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
    <form method="post" action="/">
        <div class="container" style="background: #efefef; padding: 20px;">
            <label>Encrypt and decrypt text with AES algorithm</label>
            <textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
            <br>
            <br>
            <textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
            <br>
            <br>
            <label>SBox :</label>
            <div>
                <div class="s-box-radios">
                    <ul class="sbox">
                        <li>
                            <label>SBox 1
                                <input id="sbox1" name="sboxOption" type="radio" value="option1"  required/>
                            </label>
                        </li>
                        <li>
                            <label>SBox 2
                                <input id="sbox2" name="sboxOption" type="radio" value="option2" />
                            </label>
                        </li>
                        <li>
                            <label>SBox 3
                                <input id="sbox3" name="sboxOption" type="radio" value="option3" />
                            </label>
                        </li>
                        <li>
                            <label>SBox 4
                                <input id="sbox4" name="sboxOption" type="radio" value="option4" />
                            </label>
                        </li>
                    </ul>
                </div>
                <div class="s-box-display">
                    <textarea rows="5" cols="10"></textarea>
                </div>
            </div>
            <div class="clear"></div>
            <br>
            <label>Result of Decryption in plain text</label>
            <textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
            <br>
            <input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
            <input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
        </div>
    </form>

  <script>
    function valEncrypt()
    {
        var inputText = document.getElementById('inputText');
        var inputkey = document.getElementById('inputKey');

        if (inputText.value.length <16)
          {
            doAlert(inputText);
            return false;
          }
        else
          {
            removeAlert(inputText);
          }
        if (inputkey.value.length <16)
          {
            doAlert(inputkey);
            return false;
          }
        else
          {
            removeAlert(inputkey);
          }


    }
    function  valDncrypt()
    {
       var inputkey = document.getElementById('inputKey');
       if (inputkey.value.length <16)
          {
            doAlert(inputkey);
            return false;
          }

      alert('!Success');
    }
    function doAlert(element){
      element.style.border = "1px solid #FF0000";
    }
    function removeAlert(element){
      element.style.border = "1px solid #000000";
    }

  </script>
</body>
</html>