I have a form which contains inputs with required tag. It normally validates when I click on an input of type submit.
But I wanted to be able to initiate that process programmatically using javascript. or when an element outside of the form is clicked.
Is this possible? how can I do this?
function validateAndSubmit(){
//what can I do here to initiate same process?
//tried
document.querySelector("form").submit() //this one submits without validating
document.querySelector("#submitter").click() //no such function as this
}
<form>
<input required placeholder="name"/>
<input id="submitter" type="submit"/>
</form>
<button onClick=validateAndSubmit()>Send</button>
I want to do this from other event handler functions too. Is there a way to do this?
Thanks
You have to first focus on the form with the focus() method:
function validateAndSubmit(){
document.querySelector("form").focus()
document.querySelector("#submitter").click()
}
<form>
<input required placeholder="name"/>
<input id="submitter" type="submit"/>
</form>
<button onClick=validateAndSubmit()>Send</button>
Related
I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>
I have a very simple form:
<form>
<fieldset>
<input id="in1" type="text" data-validate="required">
</fieldset>
<fieldset>
<input id="in2" type="text" data-validate="required">
</fieldset>
<input id="btn" type="button" value="Insert your datas" onclick="insert()">
</form>
If third input (id:"btn") had type="submit", notify/verify would work well.
I don't need to submit this form (because I have to launch an insert() function on button onclick),
so I deleted the submit type of my button and unfortunately no notifications appear on my page now.
I may add an handler (like this: $(".elem-demo").notify("Hello Box")) as notify docs suggest, but that is a custom notification, good, but I want to take advantage of verify.js data-validate..no extra-code required for a simple validation like "required" or "number".
How can I fix that?
I wish I was clear of my issue and thanks to answer me.
You can keep the button type submit and can override the default form submission behavior on submit button click via event.preventDefault()
<form id="my-form" onSubmit="myFunction(event)">
<fieldset>
<input id="in1" type="text" data-validate="required">
</fieldset>
<fieldset>
<input id="in2" type="text" data-validate="required">
</fieldset>
<input id="btn" type="submit" value="Insert your datas" onclick="insert()">
</form>
This your function which will be called on form submission.Access the form via its id and call validate to check form for errors.
Calling validate will trigger validation on every element in the form. It accepts a callback function callback(success) which will be called after validation.
function myFunction(e){
e.preventDefault();
$("#my-form").validate(callbackFunction);
// call your other function
}
I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>
I was wondering how can I submit div data to MySQL. Im not used to javascript so I dont really know whats happening on the javascript part but how can I get or input the action="" part and method="" part and can I or should I add value="" to the hidden input???
Form html code:
<form onsubmit="document.getElementById('hidden_data').value=document.getElementById('showing_data').innerHTML;">
<input id="hidden_data" name="data" type="hidden"/>
<div id="showing_data" class="commenttext" contenteditable="true"></div>
<input type="submit" Value="Enter" id="submitthis">
</form>
Use the hidden field inside the form tag and use the JavaScript to put the value inside it. You can get the hidden field in the $_POST['hydName'].Put the data on the click of the submit button into the hidden field. Keep your action and method of the form same as required. After the click event is fired, it will submit the form to its action URL
<input type="submit" onclick="document.getElememtById('hidden').value = document.getElementById('div').innerHtml;" />
I have this simple form:
HTML
<form>
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton"
onclick="doSomething();" type="submit">Create!</button>
</form>
JS
function doSomething() {
var name, email;
name = document.getElementById("eName").value;
email = document.getElementById("Email").value;
putElementsIntoTheDOM(name, email);
}
When the user inputs some information I want to populate the DOM with the user input.
The example above works. But I think it can be done better. I just don't know how.
How can I wire the <button> so that when the user clicks it the form values are passed
to the function doSomething()?
Also, since I'm not sending the form values anywhere except populating the DOM, how can I
prevent the submission?
I've seen something like this but I can't get it too work.
<button id="create" class="boton" onclick="doSomething(this.form);"
type="submit">Create!</button>
If you don't want to send the form values anywhere, then you just need to remove type="submit" from your button.
Your example code works fine. I'm not sure what you mean by a 'better' way. More modern/idiomatic javascript would not be using the onclick attribute, but instead binding doSomething to the button. Using jQuery, that would look like:
$("#create").click(doSomething);
First of all you have to update your function declaration to be able to receive the variables you want to send
function doSomething(name,email) {
}
Secondly, if you have to send values of some fields to that function, you can do so on button click like this.
<button id="create" class="boton" onclick="doSomething(document.getElementById('eName').value,document.getElementById('Email').value);" type="submit">Create!</button>
However, using unobtrusive javascript is recommended, and for that jQuery is one of the options you can use for passing variables to your function neatly.
There is a difference between the type="submit" and type="button" that I didn't realize.
Also, the button and submit types react differently with onclick and onsubmit events.
For example
<form onclick="doSomething()">
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton" type="button">Create!</button>
</form>
Notice that at the top of the form there is onclick.
The onclick is fired whenever you focus on an input element, and of course if you click the button.
Changing the form to <form onsubmit="doSomething(); but not changing the type="button" doesn't do anything. Clicking the button doesn't trigger the function.
By changing the type="submit"and keeping the head <form onsubmit="doSomething(); triggers the function when the button is clicked. A nice added functionality to this is that if you have any <input ... required="required"> the submit will only work if those fields are filled in (and your form will let you know about the required fields).
To prevent the submission/refreshing (since I'm only populating the DOM with user input) adding return false at the form head prevents submission
<form onsubmit="doSomething(); return false">.
Finally, to get the form values adding this:
<form onsubmit="doSomething(this); return false> and then
function doSommething(formInfo) {
var name = formInfo.eName.value;
var email = formInfo.Email.value;
...
}