Skip to content

Instantly share code, notes, and snippets.

@mems
Created August 25, 2014 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mems/97a733d9c787dcf99cff to your computer and use it in GitHub Desktop.
Save mems/97a733d9c787dcf99cff to your computer and use it in GitHub Desktop.
JS Submit form programmatically http://dabblet.com/gist/97a733d9c787dcf99cff
<p>Submit programmatically not work correctly. Some browsers send directly the form without trigger submit event and/or execute validation.</p>
<p>Submit the form! If the field is empty, you should see the native validation display an error message (for browsers that support HTML5 form validation). Then a confirm dialog box should ask you if you want to search the given term on Google Search</p>
<form id="form" action="http://google.com" target="_parent">
<p><label for="term">Search on Google:</label> <input type="text" name="q" id="term" value="" required></p>
<fieldset>
<legend>Programmatically form submition</legend>
<p><label for="method">Method:</label> <select id="method">
<option value="method">form.submit()</option>
<option value="event">Trigger submit event</option>
<option value="button">Virtual click on hidden submit button</option>
</select></p>
<p><button type="button" id="bt">Submit</button></p>
</fieldset>
<fieldset>
<legend>Simple way (a submit button)</legend>
<p><input type="submit"></p>
</fieldset>
</form>
var form = document.getElementById("form");
var method = document.getElementById("method");
var term = document.getElementById("term");
var bt = document.getElementById("bt");
form.addEventListener("submit", function(event) {
if(!window.confirm("Do you want to search \"" + term.value + "\" on Google Search?")){
event.preventDefault();
}
});
bt.addEventListener("click", function(event) {
switch(method.value){
// Normal way. Could skip submit event and validation
case "method":
form.submit();
break;
// Use an event to submit. Could skip validation or simply don't send form!
case "event":
// Dispatch event
var submitEvent;
try{
// DOM4
submitEvent = new Event("submit", true, true);
}catch(error){
// DOM2
submitEvent = document.createEvent("Event");
submitEvent.initEvent("submit", true, true)
}
form.dispatchEvent(submitEvent);
break;
// Use an hidden button and emulate a click on it
case "button":
var button = form.ownerDocument.createElement('input');
// Hide it (style and for ATs)
button.style.display = "none";
button.tabIndex = -1;
button.setAttribute("aria-hidden", "true");
button.setAttribute("role", "presentation");
button.type = "submit";
form.appendChild(button).click();
form.removeChild(button);
break;
}
});
{"view":"split-vertical","fontsize":"100","seethrough":"","prefixfree":"1","page":"javascript"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment