Access the value assigned to the clicked submit button with JavaScript - javascript

I noticed one pecular thing. When there are several submit buttons in your HTML form like so:
<button type="submit" name="submit_button", value="b1"></button>
<button type="submit" name="submit_button", value="b2"></button>
<button type="submit" name="submit_button", value="b2"></button>
..and you do this:
var $form = $('#my_html_form');
$form.submit(function() {
if (!checkPassed && !hasRequiredValue) {
bootbox.confirm('Are you sure that you don\'t need <strong>{requiredValue}</strong> parameter?', function(result) {
if (result) {
checkPassed = true;
$form.submit();
}
});
return false;
}
});
the field submit_button does not get submitted at all, it's just not present in the request data.
Would there be a way to force JS to submit data together with the value of the submit button clicked?
I will only add that if the form is submited with PHP and not JS, the submit_button field is present and has the value of b1, b2, or b3 - depending on which button was clicked.
P.S. I just thought that the source of the problem might be that I'm using <button> instead of <input>. However, as I said, it's all good with PHP.

Only a successful submit button will be included in the form data.
A successful submit button is one that is used to submit the form.
Your JavaScript runs on the submit event and:
Always cancels the submission of the form
Sometimes submits the form with JS
Since you are submitting the form with JS instead of the submit button, none of the submit buttons are successful.
Change your JS so that it:
Sometimes cancels the submission of the form
Such:
$form.submit(function() {
// Add a NOT condition here
if (!<someCondition>) {
return false;
}
return true;
});
Regarding the update:
OK, so you are always canceling the submission, and using a DOM based widget to ask for confirmation.
In that case, you need to capture the value of the submit button separately.
The information isn't exposed to the submit event so you need to do it on the click event of the submit button.
Add a hidden input to your form:
<input type="hidden" name="submit_button">
Then add another event handler:
$form.on("click", '[name="submit_button"]', function (event) {
$form.find('[type="hidden"][name="submit_button"]').val(
$(this).val()
);
});

Yes you can get the value of the button
$('button').click(function(event) {
var button = $(this).data('clicked', $(event.target));
var value = button.val();
});

Here you go.
$("button[name=submit_button]").click(function() {
alert($(this).val());
});
Fiddle: http://jsfiddle.net/tw698hvs/

Related

Submit form with jquery which has multiple submit buttons without click trigger?

Imagine this :
<form id="form">
<input type="text">
<button type="submit" name="submit1" value="1">something1</button>
<button type="submit" name="submit2" value="2">something2</button>
<button type="submit" name="submit3" value="3">something3</button>
</form>
First of all when I write $('#form').submit() which submit value will be sent? the first one?
Second of all How can I submit the form without the click trigger event with the value I want? Is it possible at all? For example submitting the form with the 2 submit value.
The reason I want do this is to have confirmation popup with sweetalert before sending my form so here it is :
$('form').on('submit',function(e){
form = $(this);
e.preventDefault();
swal({'some dialog'},function(isConfirm)
{
if(isConfirm)
form.submit;
\\If I use the click trigger I will get stuck in here again.
})
});
There is an alternative - use the FormData You can create an instance of a FormData, add your html form, modify entries, and send it. Everything is under your control here then.
EDIT: Based on your edit, it seems you have the problem of resubmitting the form. You can handle it like this.
var form = document.querySelector('form');
form.addEventListener('submit', {
confirmed: false,
handleEvent: function (event) {
if (this.confirmed)
return;
event.preventDefault();
doconfirm((confirmed) => {
if (confirmed) {
this.confirmed = true;
form.submit();
}
})
}
}, false);
Or you can solve your problem by unbinding the submit handlers after validation and submit it again: $('form').off('submit').submit()
As #Scott Marcus explained, the value of named buttons will be submitted when the form is sent to the server. However in your case, this won't help because you want to perform some logic before submitting it to the server.
The issue is that jQuery has no way to determine which button was clicked because it doesn't provide the submit button values when you look at the form data via $.serialize(), and there is no easy cross-browser friendly way to check the button that triggered the $.submit() event without using click.
So, the only workaround would be to handle the click event of the 3 buttons and store some value that is checked before you submit the form as described in this answer: How can I get the button that caused the submit from the form submit event?
Example: http://codeply.com/go/Wj85swRyfX
Let's take your questions one at a time...
First of all when I write $('#form').submit() which submit value will
be sent? the first one?
When a form is submitted, ALL form elements that nave a NAME attribute will submit their value (even if the value is an empty string) to the form's ACTION destination. So, in your case, all 3 of your buttons have a name attribute and so all 3 buttons will submit their name/value pairs.
Usually, we don't put a name attribute on the submit button because we only want it to trigger the submit, not actually use it as a data container. And, we usually include only a single submit button under most circumstances.
Second of all How can I submit the form without the click trigger
event with the value I want? Is it possible at all? For example
submitting the form with the 2 submit value
You would use:
$('#form').submit()
to manually cause the submit, but you'd need to have an if() statement that has logic that determines which value is appropriate to submit. Instead of the value being stored in a button, you could use a hidden form field, like this:
<form id="form">
<input type="text">
<input type="hidden" name="hidden" value="">
<button type="submit">something3</button>
</form>
JavaScript:
$("#form").on("submit", function(evt){
// Stop the form submission process
evt.preventDefault();
// Logic that sets hidden input field to correct value:
if(condition1){
$("input[type=hidden]").attr("value", "1");
} else if(condition2) {
$("input[type=hidden]").attr("value","2");
} else {
$("input[type=hidden]").attr("value","3");
}
// Manually submit the form
$("#form").submit();
});
I suggest to use hidden input tag to make the logic clear.

jQuery one function not working as expected

I have the following jsp:
...
<script type="text/javascript">
$(function() {
// prevent multiple submissions
$('#saveCallListBtn').one("click", function() {
$('#callListForm').submit();
});
});
...
</script>
...
<form:form id="callListForm" commandName="callList" action="${contextPath}/calllist/save" method="POST" htmlEscape="true">
...
<td colspan="2" style="text-align: center">
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
</td>
...
</form:form>
The behavior I am looking for is to only all the form to be submitted once no matter how many times the save button is clicked. Using the jQuery .one function, I can get the above code to correctly work. As the form will submit multiple times if I click more than once.
The following code will work fine:
$('#saveCallListBtn').on("click", function() {
$(this).prop("disabled", true);
$('#callListForm').submit();
});
But I am interested to know what I am doing wrong with the .one function.
Note the type here:
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
A submit button in a form will submit the form, no JavaScript required. So when your handler is automatically removed, on the next click the default handling (submitting the form) occurs, courtesy of the browser.
The only reason you're not seeing the form submitted twice on first click, I suspect, is that the act of submitting the form begins the process of tearing down the page to make room for the result of the submission.
FWIW, I would suggest that you not have a click handler on the button, but rather a submit handler on the form that, if all is well and it's going to allow submission to occur, disables the button and sets a flag to prevent future form submission, since forms can be submitted in multiple ways. (On some forms, pressing Enter in a text field will do it, for instance.)
E.g.:
$("#callListForm").on("submit", function(e) {
var $btn = $("#saveCallListBtn");
var valid = !$btn.prop("disabled");
if (valid) {
// ...do any other validity checks you may want, set `valid` to false
// if problems encountered...
}
if (valid) {
$btn.prop("disabled", true);
} else {
e.preventDefault();
}
});
The jQuery one function will execute the event handler only once. However, the default behaviour of the element clicked will execute indefinitely.
Change the type of the button to button, such that it has no default behaviour:
<input id="saveCallListBtn" type="button" value="Save" class="button-med"/>

Why does the text change back without 'return false'

I have a simple HTML button on my form, with script as follows:
$(document).ready(function () {
$("#btn1").click(function () {
$("#btn1").text("Button clicked");
return false;
});
});
With the return false, it works as I expect - I click the button, and its text changes to 'Button clicked'. Without the 'return false', it changes, but then changes back.
Complete JQuery noob here, why do I need the 'return false'?
A <button> in a form submits the form, which is why it turns back, the page reloads resetting everything javascript changed, so you see the change, and it immediately reloads the page when the form submits.
The return false prevents the form from submitting when clicking the button.
Note: the <button> element has a default type of submit, so it will always submit the form it's nested inside.
Like #adeneo said, your form is being sent out so the page will reload. Additionally, if you don't want to use return false; you can use preventDefault() by passing an event parameter to your function as such:
$(document).ready(function () {
$("#btn1").click(function (ev) {
ev.preventDefault();
$("#btn1").text("Button clicked");
});
});
Hope this helps,
If the <button> was not intended to submit the form, then instead of using return false; or other workarounds make the button the proper type.
<button id="btn1" type="button">
And it will stop submitting when clicked. The reason it does now is because the button's default type is submit (it has 3 possible types: submit, button, and reset).

Disable form auto submit on button click

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}

jQuery form submit: Any way to know what element triggered the submit?

I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.
$('form').submit(function() {
...code done here to validate form fields
});
The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?
I asked this same question: How can I get the button that caused the submit from the form submit event?
The only cross-browser solution I could come up with was this:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.
well this will only fire if the type of the input button is like so:
<input type='submit' ...
so make sure the cancel button does not have type='submit' and it should work
EDIT
This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.
#Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:
$('form').submit(function(e){
if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
//don't validate
}
else{
//validate
}
});
var myForm = $('form');
$('input[type="submit"]',myForm).click(function(e) {
var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
//do other things here
});
EDIT
.submit(function(event){
var target = event.originalEvent.explicitOriginalTarget.value;
//But IE does not have the "explicitOriginalTarget" property
});

Categories