Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .submit() overrides required field

I have a form that I want a modal to confirm before sending. I do this with JavaScript. I open the Modal and there I use the .submit() function but it sends the form without respecting the "required" fields.

Here's an example I made with http://www.w3schools.com/:

<!DOCTYPE html>
<html>
<body>

<form id="some" action="demo_form.asp">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>

<p><strong>Note:</strong> The required attribute of the input tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.</p>
<button type="button" onclick="document.getElementById('some').submit();">Send anyway</button>
</body>
</html>

Here's the fiddle: http://jsfiddle.net/fmpk1h1m/

What I want is the same effect of the required attribute whether I send the form directly or by JavaScript.

like image 929
Eduardo Galindo Franco Avatar asked Aug 19 '14 21:08

Eduardo Galindo Franco


1 Answers

Trigger the form submit button click:

var form = document.getElementById('form');
var submitButton = document.getElementById('submit-button');
var sendButton = document.getElementById('send-button');

sendButton.addEventListener('click', send);

function send(e) {
    submitButton.click();
}

http://jsfiddle.net/8rwfspbt/1/

like image 56
Miguel Mota Avatar answered Oct 16 '22 23:10

Miguel Mota