8

I have created a HTML form which has two buttons (instead of a submit button), each programmatically sending the form to a unique form action address.

<form id="formExample">
<input type="text" id="input1" required>
<label type="button" onClick="form1()">Form Action 1</label>
<label type="button" onClick="form2()">Form Action 2</label>
</form>

The scripts:

form = document.getElementById("formExample");

function form1() {
    form.action="example1.php";
    form.submit();
}
function form2() {
    form.action="example2.php";
    form.submit();
}

Work well, responding to which button you press. However, the same html form validation that worked before (when using a 'submit' button), no longer shows a hint and the form sends regardless of whether there is input or not.

I have read that because I am calling the form.submit() programmatically, it bypasses the onSubmit() function of a form, which is where the validation takes place.

My question is: Can I programmatically force the onSubmit() so that I get the validation pop up? I must make clear that I am NOT wanting to create a JavaScript form validation, i.e. using an alert; rather, use JavaScript to enforce the HTML validation as found here, when you click submit: https://jsfiddle.net/qdzxfm9u/

dantan04
  • 313
  • 1
  • 5
  • 13
  • 4
    You can merely change your button's type from `button` to `submit` and drop the `form.submit()` from your JS part. – cFreed Dec 21 '15 at 19:38
  • 1
    If you can use JQuery, have a look at [this answer](http://stackoverflow.com/a/11867013/4341456). – Daniel Dec 21 '15 at 19:40
  • Cheers @cFreed, That has solved the problem! If you'd like to provide it again in the answer part, I will happily accept as the solution. Thanks! – dantan04 Dec 21 '15 at 20:00
  • That's done! Glad to help, and glad you accept my answer :) – cFreed Dec 21 '15 at 20:13
  • @dantan04, you may consider `` instead of `` as the latter is not a valid HTML, put your form html inside the body in https://validator.w3.org/nu/#textarea and click on *check* – Mi-Creativity Dec 21 '15 at 22:00

4 Answers4

3

Maybe something like this :

var form = document.getElementById("formExample");

function form1() {
  form.action="example1.php";
}

function form2() {
  form.action="example2.php";
}
<form id="formExample">
  <input type="text" id="input1" required>
  <input type="submit" onClick="form1()" value="Form Action 1" />
  <input type="submit" onClick="form2()" value="Form Action 2" />
</form>
  • This is spot on! The only reason why I haven't accepted it as the answer, is because someone came up with the same idea just before you on my comments feed. I appreciate the effort. – dantan04 Dec 21 '15 at 20:18
3

You can merely change your button's type to submit and drop the form.submit() from your JS part.

So the HTML part becomes:

<form id="formExample">
<input type="text" id="input1" required>
<button type="submit" onClick="form1()">Form Action 1</button>
<button type="submit" onClick="form2()">Form Action 2</button>
</form>

This way, clicking any button does submit by itself, but before is executed the JS part:

form = document.getElementById("formExample");

function form1() {
    form.action="example1.php";
}
function form2() {
    form.action="example2.php";
}

EDIT

Warning: I originally based my solution on a copy of the OP HTML part, where the "pseudo-buttons" used a strange element <label type="input"...>, so I read (too quickly) as if it was <button type="button"...> and simply changed type from input to submit!
This way, it couldn't work as expected.

It is now corrected in the above code.

cFreed
  • 4,252
  • 1
  • 21
  • 33
  • "*clicking any button does submit by itself, but before is executed the JS part*" he has to execute the js part since he needs to decide which action has to be attached to the form – Mi-Creativity Dec 21 '15 at 20:14
  • @Mi-Creativity. I don't understand what you mean. I agree that the JS part must be executed, but it's just what happens. – cFreed Dec 21 '15 at 21:05
  • I mean if the JS part won't be executed what will be the `action=` attribute of the form - *`example1.php` or `example2.php`* - considering it is only set through JS? – Mi-Creativity Dec 21 '15 at 21:08
  • @Mi-Creativity. Strictly responding, if the JS part is not executed then we know that default applies, i.e. the current script is used as `action` value. But in the current case, this will not happen, since it is written so that each submit button has its own `onclick` event firing the needed handler. – cFreed Dec 21 '15 at 21:16
  • Just bear with me please, so the JS part *will* be executed on click then the form submits according to your code, check this link http://phpfiddle.org/lite/code/rt18-mzu9 - *hit run to execute* - which is exactly your code with a bit of CSS, I wonder if it shows the HTML validation and submits and works for you. – Mi-Creativity Dec 21 '15 at 21:46
  • Now check http://phpfiddle.org/lite/code/4xge-ixhz which exactly the code provided by @jean-baptiste-rudant , it works like it should, it does shows the HTML validation on the text field, and it does submit the form to the corresponding PHP page – Mi-Creativity Dec 21 '15 at 21:52
  • @Mi-Creativity.Woh! It took me time to realize where was the difference! Now I understand what you mean... and I keep confused. First you must know that I primarily put my solution in a comment, since it was only a guess, not tested. Then the OP guy said "Thanks, it works, you can put it in an answer", and I did it. So I wonder why it found it working. Moreover, I see that my version is not enough for validation to fire, but I can't figure out why adding `value` in the @jean-baptiste-rudant does. I'll examine this deeper, and alert the OP guy if he must transfer its "accept" to @jean-baptiste! – cFreed Dec 21 '15 at 22:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98614/discussion-between-cfreed-and-mi-creativity). – cFreed Dec 21 '15 at 22:13
  • Thanks for your understandng, and it wasn't because the `value` attribute it was because of in your code, as in the OP code, it is ` – Mi-Creativity Dec 21 '15 at 22:13
  • Also I think the OP is free to pick the answerwith the code which works for him he is free but IMO I think it'll be misleading for other people now or in the future when they read the question and its answers – Mi-Creativity Dec 21 '15 at 22:18
  • @Mi-Creativity. Now all is clear. See my edit. Note that when I found where was the trick I wanted to give the explanation in a comment but was automatically put in chat, while I can't: sincce my mother language is not English I'm not able to follow discussion this way :( – cFreed Dec 21 '15 at 22:27
  • your comment "*You can merely change your **button's** type from button to submit and drop the form.submit() from your JS part*" was so correct and now the answer too, thanks and UpVoted! – Mi-Creativity Dec 21 '15 at 22:31
  • @Mi-Creativity. Thanks for the fair! – cFreed Dec 21 '15 at 23:51
2

How about making a dropdown list - could be radio buttons instead - containing the form two actions with one submit button like in this JS Fiddle, then having one function on form submit

var form = document.getElementById("formExample"),
    select = document.getElementById("slct");

form.addEventListener('submit', function() {
  if (select.value == 1) {
    form.action = "example1.php";
  } else {
    form.action = "example2.php";
  }
  // alert for demo only
  alert(form.action);
  form.submit();
});
<form id="formExample">
  <input type="text" id="input1" required>
  <select id="slct" required>
    <option></option>
    <option value="1">Form Action 1</option>
    <option value="2">Form Action 2</option>
  </select>
  <button type="submit">Submit</button>
</form>
Mi-Creativity
  • 9,381
  • 10
  • 35
  • 46
-1
function togglePassword(el){
     var checked = el.checked;
     if (checked) {
        document.getElementById("password").type = 'text';
        document.getElementById("toggleText").textContent= "Hide";
     } else {
        document.getElementById("password").type = 'password';
        document.getElementById("toggleText").textContent= "Show";
     }
  }

  function login()
  {
     var uname = document.getElementById("uname").value;
     var password = document.getElementById("password").value;
     if(uname === '')
     {
        alert("Please enter the user name.");
     }
     else if(password === '')
     {
        alert("Enter the password");
     }
     else
     {
        alert('Login Successful. Thank You!');
     }
  }

  function clearFunc()
  {
     document.getElementById("uname").value="";
     document.getElementById("password").value="";

<script type="text/javascript">
      function togglePassword(el){
         var checked = el.checked;
         if (checked) {
            document.getElementById("password").type = 'text';
            document.getElementById("toggleText").textContent= "Hide";
         } else {
            document.getElementById("password").type = 'password';
            document.getElementById("toggleText").textContent= "Show";
         }
      }

      function login()
      {
         var uname = document.getElementById("uname").value;
         var password = document.getElementById("password").value;
         if(uname === '')
         {
            alert("Please enter the user name.");
         }
         else if(password === '')
         {
            alert("Enter the password");
         }
         else
         {
            alert('Login Successful. Thank You!');
         }
      }

      function clearFunc()
      {
         document.getElementById("uname").value="";
         document.getElementById("password").value="";
      }  
   </script>     
/* heading  */
h1 {
    display: block;
    font-size: 2em;
    font-weight: bold;
    /* padding: 0% 1% 3% 6.5%; */
    margin: 0% 35% -10% 36%;
}


h1:hover{
  color:#4499d9 ;
  transform: translateY(-5px);
}


/* bg image */
body {
  background-image: url('img/bg4.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100% 100%;
}


/* Bordered form */
form {
 /*  border: 13px solid black; */
  width: 27%;
  height: auto;
  position: absolute;
  left: 10%;
  margin-left: -3px;
  top: 18%;
}

/* Full-width inputs */
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

/* Set a style for all buttons */
button {
  background-color: #17234b;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 49%;
}

/* Add a hover effect for buttons */
button:hover {
  background-color: #4499d9;
   transform: translateY(-5px);
  box-shadow: 1px 3px 7px #6f6d72;
}

#toggleText {
    display: block;
}


/* Center the avatar image inside this container */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
}

/* Avatar image */
img.avatar {
     width: 30%;
    border-radius: 20%;
     box-shadow: 1px 3px 9px #6f6d72;
}

img.avatar:hover{
   transform: translateY(-5px);
  box-shadow: 7px 9px 9px #6f6d72;
}

/* Add padding to containers */
.container {
  padding: 16px;
}

span.buttons{
    width: 100%;
    display: flow-root;
}

#toggleText{
  float: left;
}

#toggle{
  float: left;
}
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
   <h1>LOGIN PANEL</h1>
   <!-- Login Form -->
   <div class="form"> 
      <form >
         <div class="imgcontainer">
            <img src="img/Login.jfif" alt="Login Avatar" class="avatar">
         </div>
         <div class="container">
            <label for="uname"><b>Username</b></label>
            <input type="text" placeholder="Enter Username" id="uname" name="uname"/>
            <label for="password"><b>Password</b></label>
            <input type='password'placeholder="Enter Your Password" name="password" id='password'/>
            <input type='checkbox' id='toggle' onchange='togglePassword(this)'><span id='toggleText'>Show</span>
            <span class="buttons">
               <button type="submit" value="Reset" onclick="clearFunc()" class="btn">Reset</button>
               <button type="submit" value="Login" class="btn" onClick="login()">Login</button>
            </span>
         </div>
      </form>
   </div> 


 
</body>
</html>
  • Welcome to Stack Overflow. Code without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See [How to Answer](https://stackoverflow.com/help/how-to-answer). – Sfili_81 Jul 12 '21 at 11:34