Select submit button of specific form for click event - javascript

If I have the following form, how can I select the submit button based on the form ID to be used for a click event?
<form id="login">
<input type="text" name="email">
<input type="text" name="password">
<input type="submit" name="submit">
</form>
Something like the following works, but it can't just be input[name=submit] because there may be more than one on the page.
$('input[name=submit]').click(function (e) {
e.preventDefault();
console.log('clicked');
});

This will automatically select the form's submit control:
$('#login :submit').click(...);
http://api.jquery.com/submit-selector/
Cheers

Use :
document.querySelectorAll("input[type=submit]")[0].click();

Use
$('#login input[type="submit"]')
You can read http://www.w3.org/TR/selectors/ for all CSS selectors.. (jQuery supports all default selector + more http://api.jquery.com/category/selectors/)

Related

i am using required html tag for input fields but its not working [duplicate]

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>

Validate input type=number min=... single field, no form [duplicate]

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>

populating a field value based on the button clicked

I have a html form with a hidden field and 2 submit buttons. Based on what button in clicked ( trial or buy) I need to set the promo code field ( with "trial" as promo code for trial button and "buy "as promo code for buy button.
I am not sure how I could read what button is clicked in java script. I have a java script already in place that is copying email ID into another field on hitting submit. I'd like integrate the java script with existing one.
HTML code:
<form>Email:
<input type="text" name="email">
<br>
</label><input type ="hidden" name="retype-email">
<br>
<input type="hidden" name="PromoCode" value="" method="post">
<input class="Orange_button" type="submit" value="Start my free trial">
<input class="green_button" type="submit" value="Buy it now">
</form>
JS Fiddle: http://jsfiddle.net/x1bdgvyt/3/
It looks like the best solution is to manually track which button was clicked by subscribing to their "click" events.
Working Example here (jsFiddle)
HTML
<form>Email:
<input type="text" name="email">
<br>
</label><input type ="hidden" name="retype-email">
<br>
<input id="promo-code" type="hidden" name="PromoCode" value="" method="post">
<input class="Orange_button" type="submit" value="Start my free trial" data-code="trial"/>
<input class="green_button" type="submit" value="Buy it now" data-code="buy"/>
</form>
JavaScript
$('form').on('submit', function(e){
$('[name="retype-email"]').val($('[name="email"]').val());
var value = $("input[type=submit][clicked=true]").data("code");
$("#promo-code").val(value);
alert(value);
e.preventDefault()
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Note that I added a data attribute to the submit buttons so that we can store the code that should be added.
source: jQuery: how to get which button was clicked upon form submission?
First, add 'data-type' (or whatever the name, most important is the prefix data-) to your inputs:
HTML
<input data-type="trial" class="Orange_button" type="submit" value="Start my free trial">
<input data-type="buy" class="green_button" type="submit" value="Buy it now">
Then, change a bit your javascript in order to grab the data-type value and populate your field with it:
Javascript
$('[type="submit"]').on('click', function(e) {
// populate your duplicated 'email' field
$('[name="retype-email"]').val($('[name="email"]').val());
// populate your 'code' field : grab the data-type attribute added in your HTML
$('[name="PromoCode"]').val($(this).data('type'));
// finally, submit the form
$('form').submit();
});
Quick warning: you should consider using IDs or classes instead of working with wide selectors like [attr], it could be an issue if you have more than one form in your page (and it's a better practice anyway)
Here is my solution:
$('#usuario_form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
You can have access to OriginalEvent Submitter Id to identify wich button was clicked

how to submit the values in the form in javascript when there are 2 submit values?

I have one form where there are 2 inputs those are submit type of inputs like this.
<form>
<input type="text" name="payee" value="">
<input type="text" name="amount" value="">
<input type="text" name="date" value="">
<input type="submit" name="deposit" value="Distribute">
<input type="submit" name="distribute" value="Deposit">
</form>
In jQuery like this:
$("form submit").click(function() {
// i wrote code.
}
If I click on the deposit button some action should occur. If I click on the distribute button some other action should occur.
First of all you need to change your submit inputs to buttons (or at least one of them) as 2 submit buttons in 1 form is invalid. Then give each button its' own Id.
<input type="button" name="deposit" value="Distribute" id="distribute">
<input type="button" name="distribute" value="Deposit" id="deposit">
Then, in jQuery you can then use the Id of each button to run specific code when it is clicked, like this:
$("#distribute").click(function() {
// code to run when distribute is clicked
}
$("#deposit").click(function() {
// code to run when deposit is clicked
}
insert another input type :
<input type="hidden" name="hf" id="hf" value="">
and
$("form :submit").click(function() {
if ($(this).attr('id')=='distribute') $("#hf").val('sent by distribute');
else $("#hf").val('sent by deposit');
}
and in the server you can see who send by reading the hiddenField value ( hf)
You can add a custom attribute on your buttons in document.ready function and on click of the button you can identify which button has posted an request to form.
Example to add custom attribute
<input type="submit" id="deposit" value="Distribute">
<input type="submit" id="distribute" value="Deposit">
$(function () {
$("#deposit").attr('isDeposit','1');
$("#distribute").attr('isDeposit','0');
});
and on submit click
$("form submit").click(function()
{
var identifyButton = $(this).attr('isDeposit');
}
some thing like this.
Try to use the jQuery submit() function, like this:
$('#deposit').submit(function(){
//Code to run
});
It's better because you can cancel the client event, if some field is wrong.
http://api.jquery.com/submit/
You don't need a plugin to do it, however there's a lot of them:
http://www.designyourway.net/blog/resources/55-jquery-form-plugins-to-download-and-use/

Jquery submit form error

I have a form which I want to submit upon button click which is outside the form, here is my HTML :
<form id="checkin" name="checkin" id="checkin" action="#" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
</form>
Here is my jQuery :
$("button").live('click', function() {
$("#checkin").submit();
});
$("#checkin").live('submit', function() {
});
When I click submit button inside the form its submitting ok, but its not submitting when I click on the button which is outside the form tags, why? how can I fix this ?
You are selecting all the <button> elements but you are trying to select an <input>.
It works when it is inside the form because the the normal submit functionality runs.
Change the selector to match the element you actually have: input[type=submit]
Better yet, forget about the JS and just structure your HTML better so that the submit button is inside the form.
If you're handling the form processing using JavaScript, then you'll want to return false in your button and form processing code.
I was able to achieve identical results using the JavaScript below, and the two HTML examples (with the button inside and outside of the form element).
JavaScript/jQuery
$("button").live('click', function() {
$("#checkin").submit();
return false;
});
$("#checkin").live('submit', function(){
alert("Hello world!");
return false;
});
HTML Example 1
Button inside the form.
<form id="checkin" name="checkin" id="checkin" action="" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
<button>test</button>
</form>
HTML Example 2
Button outside the form.
<form id="checkin" name="checkin" id="checkin" action="" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
</form>
<button>test</button>
As I said, both examples performed as expected. You may want to double-check your button listening code to ensure that you are in fact using the button element. If you're using an element with the id attribute set to button, then you'll want to ensure you are using the proper jQuery selector:
$("#button").live('click', function() { // ...
you can have a simple hyperlink outside of your form like this
click to submit and that's all you need

Categories