Dave
Dave

Reputation: 253

How to solve validation using multiple buttons in a form

I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below

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

And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:

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

The js function looks like this:

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

Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:

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

Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?

Upvotes: 0

Views: 3354

Answers (4)

rashid
rashid

Reputation: 193

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>

Upvotes: 0

G-Host
G-Host

Reputation: 376

Watch this sample 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;">

anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.

The function didnt worked because its scope was the element, if u specify window as context your function works.

Upvotes: 1

Leo
Leo

Reputation: 930

First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.

I think the smartest way of doing it will be as follow:

Your form (without action, submit button, and method. Only identifing each component with id's):

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

Your javascript (you have to have jQuery added):

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

I hope it helps you!

Upvotes: 1

Burki
Burki

Reputation: 1216

replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.
Your Version actually has two submit-buttons, both of which will submit the form.

Upvotes: 2

Related Questions