Specifying button clicked in multiple forms in javascript - javascript

I need help with some Javascript.
Inside my html I have a form that repeated twice.
<form method='post' action='php page'>
<input type=text id=something name=something value='' />
<input type="submit" id="final_submit" value="yes">
</form>
This exact form is repeated twice. In javascript when someone clicks on the submit button I need to be able to determine which button was clicked to get the value of something in that form. Right now its automatically just getting the value for the first form even though I click the button on the second form.
Any ideas please.

As mention in the comments, using duplicate id is wrong. Here is a way to get the value of the input that will work also in using older browsers document.forms and forms.element
var forms = document.forms;
for(var i=0, l= forms.length; i++){
forms[i].addEventListener('submit', function(e){
e.preventDefault();
var form = e.target;
var value = form.elements[0].value;
})
}
This will add a submit event listener to every form in your side and that stops the event and get the value from the first input field in this form.

Is that what you need?
function determineForm(e)
{
// This prevents the form from actually being submitted.
// Just remove it when you are done debugging.
e.preventDefault();
if (document.querySelectorAll("form")[0] === e.target)
{
alert("Form1");
}
else
{
alert("Form2");
}
}
document.addEventListener("submit", determineForm, false);

Related

Having issues with setting an even listener to prevent default in input field with javascript

I am trying to make a simple password generator and i want the password generation to happen on the click of a button and that part works when i test it in the console. And now to implement it on sort of a real web page, the password generated to the input field doesn't stay!!, i know to use the .preventDefault() method but i don't know hot to apply it in this case using an event listener for when the value of the input field changes.
I couldn't add the html because it looks strange when i add it, but it looks like this:
Password: <input type="text" name="password" id="password" value="">
<button id="button" onclick="makePassword()">Get password</button>
here is my code below:
var capitalAlphabets=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var smallAlphabets=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var numbers=[1,2,3,4,5,6,7,8,9,0,];
function randomCapital(){
var capital=capitalAlphabets[Math.floor(Math.random()*capitalAlphabets.length)];
return capital;
}
function randomSmall(){
var small=smallAlphabets[Math.floor(Math.random()*smallAlphabets.length)];
return small;
}
function randomNumber(){
var number=numbers[Math.floor(Math.random()*numbers.length)];
return number;
}
var password="";
function makePassword(){
password="";
for(var i=0; i<=12; i++){
password=password+randomCapital()+randomSmall()+randomNumber();
// console.log(i + password);
}
console.log(password);
input=document.getElementById("password");
input.value=password;
}
//having issues with setting an even listener to prevent default in input field
You probably have your button inside a form so it is interpreted as a submit button (<button type="submit">). Pressing enter inside an input field inside a form will click on the first submit button inside the form. Just explicity make the button type a button so clicking it will not submit the form and refresh the page:
<button type="button" onclick="makePassword()">Get password</button>
If you want to add an event listener, use document.getElementById to get the DOM element to add a keypress event listener to and if the event's keycode is 13 (enter), prevent the default action.
document.getElementById("password").addEventListener("keypress", function(e){
if(e.keyCode==13){
e.preventDefault();
}
});
Overall, using onclick="" for a button is bad practice.
You should add an eventListener for your button instead:
var button = document.getElementById("button");
button.addEventListener("click", function(event) {
event.preventDefault();
makePassword();
});
That should work much better, let me know if you have any questions.
http://jsfiddle.net/316xjkqu/2/

JavaScript & HTML Forms: Which button is the submitter?

I am writing a JavaScript function to pre-process form data. One thing I need to know is which of a number of submit buttons was used.
Roughly, the script has the following outline.
var form=document.querySelector('form#test');
form.onsubmit=processForm;
function processForm() {
// how did I get here
}
<form id="test">
<!-- usual stuff -->
<button type="submit" name="check">Check</button>
<button type="submit" name="doit">Do Stuff</button>
</form>
I know that I could attach the function to the individual submit buttons, but it would be more resilient if I attached it to the form itself.
Is there a form property or some other method for checking which submit button was used?
Thanks
You can attach click handler to each <button> element, create a variable to store clicked button name property, or reference to element, access property or element at submit event
function processForm(e) {
e.preventDefault();
console.log(curr) // `curr`: `name` of clicked `button"` element
}
var submit = document.querySelectorAll("button[type=submit]");
var curr;
for (var i = 0; i < submit.length; i++) {
submit[i].onclick = function(e) {
curr = e.target.name; // store reference to `name`, or element
}
}
Usually the clicked submit button is sent as it is considered active.
I believe that when there is only 1 submit button the form will submit on enter but when multiple it will only submit on click.
Thus in your backend, you can just check for the existence of either form button to know which button was used.
Relevant section of HTML rfc:
https://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
However I wasn't able to find a good browser compatibility for this so your mileage may vary.
I believe the answer to my question is that you can’t. Once the submit event is activated, it doesn’t seem to know or care how it got there.
The only solution, as mentioned in my original question, is to attach a listener to the submit button[s].
Here is a stub of the processing code:
window.onload=init;
function init() {
var form=document.querySelector('form#test');
var submitButtons=form.querySelectorAll('button:not([type]),button[type="submit"],input[type="submit"]');
if(submitButtons.length) {
for(var i=0;i<submitButtons.length;i++) submitButtons[i].addEventListener('click',process);
}
function process(e) {
var submitter=this;
var form=this.form;
// etc
}
}
Oh well …

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.

Access the value assigned to the clicked submit button with 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/

Adding hidden field in beforeunload

On my page I'm using a form which on submit should get some extra hidden fields. The problem however is that I can't know the name/id of the form nor the submit button so I can't use functions like onClick etc. Therefore I'm using the beforeunload event to trigger an event when the user tries to leave the page (this includes submitting a form). I'm using the document.activeElement to find out what triggered the event and if it's a form/submit I'm adding the hidden fields to the form.
Stripping down the code it comes down to something like this:
var javascriptData = ['val1','val2','val3']; // usually gets values dynamically and can differ in size
$(window).bind('beforeunload', function(e) {
var activeForm = document.activeElement.form;
for(var i = 0; i < javascriptData.length; i++){
$(activeForm).append('<input type="hidden" name="test-data[]" value="'+javascriptData[i]+'" />');
}
return false; // just for debug purposes.
}
The code works and the element is added to the form but it doesn't show up in the $_POST on the next page. However, the final line of code (return false) creates a pop-up asking if I want to leave the page, if I stay on the page, press the submit button again and then leave the page and check $_POST, the field there. My guess is that the data for the $_POST is collected before the beforeunload function is triggered.
My question is: "Is there a way around this so I can add a hidden field to a form in the beforeunload event?".
Help is much appreciated, thanks in advance.
Why not add it to all forms on the page?
$(document).ready(function() {
$("form").append('<input type="hidden" name="test-data[]" value="test" />');
});
Like the comments above mentioned, you can just hook onto the submit event.
$('form').submit(function() {
for(var i = 0; i < javascriptData.length; i++){
$(this).append('<input type="hidden" name="test-data[]" value="'+javascriptData[i]+'" />');
}
}

Categories