Identify the value of clicked submit button with multiple submit buttons - javascript

I have situation where i need to track which submit button click in order to do set variables according to that. Below is the test code,
<script>
function submitForm(form) {
alert(document.getElementById('sb').value);
if (document.getElementById('sb').value=="One") {
//Do something
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
The alert always shows One even if i click button Two or Three. But the url change with clickable parameter. How to alert the value which is in the clickable submit button?
Note: I want a solution with out JQuery
EDIT: I change the code bit which the onsubmit call the submitForm(this);
The problem is even use document.forms[0].sb.value its undefined because document.forms[0].sb return a node list of all submit buttons as its same as with document.getElementById('sb')

Here is what I think is a simpler solution to this problem. It does not require any extra events.
<script>
function submitForm(form) {
console.log(document.activeElement.value);
if (document.activeElement.value == 'One') {
console.log("Have one.");
return false;
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
jsfiddle
What I would like an answer to is how the form is getting the query set to "?sb={value}".

I would suggest you to use buttons, instead of multiple submit buttons. In the onclick attribute of the buttons, submit the form using javascript.

You can try like this,
<form>
<input class="myButton" type="submit" name="sb" value="One">
<input class="myButton" type="submit" name="sb" value="Two">
<input class="myButton" type="submit" name="sb" value="Three">
</form>
<script type="text/javascript">
$(".myButton").on('click', function() {
alert($(this).val());
});
</script>

I'm a bit new to javascript; please forgive me if I'm wrong on this. Wouldn't it make a difference if your if statement had a 3rd = sign?
Should it be:
if (document.getElementById('sb').value === "One") {
//Do something
}
return true;

Continuing the answer above:
<script>
function m(value) {
alert(value);
}
</script>
<input type="button" value="One" onClick="m(this.value)">
<input type="button" value="Two" onClick="m(this.value)">
<input type="button" value="Three" onClick="m(this.value)">
You can of course see what's the id:
<input type="button" id='myId' value="Three" onClick="m(this.id)">

you can try with jquery something like :
$(":submit").live('click', function() {
alert($(this).val());
})

This is a non-jquery, simple solution for detecting which submit button was clicked.
<script>
function submitForm(form) {
console.log(document.getElementById('btn_clicked').value);
if (document.getElementById('btn_clicked').value === 'One') {
console.log("Have one.");
return false;
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);" ;">
<input type="hidden" name="btn_clicked" id="btn_clicked" value="">
<input type="submit" name="sb" value="One" onclick="document.getElementById('btn_clicked').value='One';">
<input type="submit" name="sb" value="Two" onclick="document.getElementById('btn_clicked').value='Two';">
</form>

Related

Form Id can't recognise addEventListener

How do I solve the error cannot read property of 'addEventListener' of null ? when I add this code,document.getElementById("myForm").addEventListener("submit", SaveBookmark) in my JS file
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="button" id="submitBtn">Submit</button>
</form>
First please notice that you're calling DOM is loaded or duplicated formID.
This code is working fine. please change <button type="button"> to be <button type="submit" .../>
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", SaveBookmark);
function SaveBookmark() {
alert('success');
}
</script>
I'm by no means an expert but to avoid that error your JS should look like this
const myForm = document.getElementById("myForm");
if (myForm) {
myForm.addEventListener("submit", SaveBookmark)
}
This ensures that your form element exists before you add the event listener
Should work easily:
document.getElementById('myForm').addEventListener('submit', function() {
alert("yes!")
})
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn">Submit</button>
</form>
It does not work because you have a
<button type="button" id="submitBtn">Submit</button>
instead of:
<button type="submit" id="submitBtn">Submit</button>
and you're trying to reach submit event.
Anyway, i recommend you not to add event listeners due to resource wasting. Use it when it's the only option.
I let you another way to reach the same with default click eventlistener:
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn" onclick="saveBookmark()">Submit</button>
</form>
<script type="text/javascript">
function saveBookmark(){
alert ("Bookmark saved");
}
</script>
You'll click on submit button anyway so, use onclick event instead of creating an eventlistener. It works simplest and waste much less resources...
And remember to add action attribute to the form, trying to re-program defined behaviour will only make your software heavy and heavy on codelines and timeloads. Thats why know the language its important.
Hope it help!

how to make an input type'button' act like type='submit'?

I have 3 input type radio:
<input type="radio" name="status">Semi-Finalist
<input type="radio" id="finalist" name="status">Finalist
<input type="radio" name="status">Reject
<input type="button" data-toggle="modal" data-target="#myModal" value="Submit">
When the user select Finalist the Modal (pop up window) show appear and ask additional questions, but If Semi-finalist or Reject is checked, submit the form when the "Submit" button is clicked. This is why I can't use type="submit"
Thank you...
UPDATE:
here is the js that show the modal
//finalist Modal
$(document).ready(function(){
$(".submitButton").click(function(){
if($('#finalist').is(':checked')) {
$("#myModalFinalist").modal('show');
}
});
});
Use type="submit".
When writing the JavaScript event handler to decide if you need to show additional questions or not, conditionally call event.preventDefault() to stop the form submission.
$("form [type='submit']").on('click', show_additional);
function show_additional(event) {
if ($("[value=finalist]:checked").length) {
event.preventDefault();
alert("Also show additional fields now");
} else {
alert("Just submit normally");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>
<input type="radio" name="status" value="semi">Semi-Finalist</label>
<label>
<input type="radio" name="status" value="finalist">Finalist</label>
<label>
<input type="radio" name="status" value="reject">Reject</label>
<input type="submit" value="Submit">
</form>
NB: The form won't actually submit in this demo because of Stackoverflow's sandboxing.
This is what i used: Thanks to #Quentin I could figure it out!
<input type="radio" name="status">Semi-Finalist
<input type="radio" id="finalist" name="status">Finalist
<input type="radio" name="status">Reject
<input type="button" data-toggle="modal" data-target="#myModal" value="Submit">
$(document).ready(function(){
$(".submitButton").click(function(event){
if($('#finalist').is(':checked')) {
event.preventDefault();
$("#myModalFinalist").modal('show');
}
});
});

prevent postback using jquery,javascript

Here is my HTML code
<form id="form1" runat="server">
<input id="q" required />
<input id="btn" type="submit" value="Search" />
</form>
I'm trying the HTML 5 required feature in asp.net. The above code works. But a post back also occurs. Is there a way to prevent the post back using JavaScript, jQuery or any other method? I tried to prevent the post back using jQuery
$(document).ready(function () {
$('#btn').click(function (evt) {
evt.preventDefault();
});
});
But this makes the required validation not to fire.
Note: There are more than one button in the form.
change "click" event to "submit", and bind it not to btn but to form
$(document).ready(function () {
$('#form1').on("submit", function (evt) {
evt.preventDefault();
});
});
Here is the updated JsFiddle which has two inputs (one is required) and two buttons (one is submit).
HTML:
<form id="form1" method="get" action="http://example.com">
<input id="q" required />
<input id="w" />
<input id="btn" type="button" value="Cancel" />
<input id="btn" type="submit" value="Submit" />
Javascript
$('#form1').on("submit", function (evt) {
evt.preventDefault();
});
If that doesn't answer your question, please elaborate

Simple JavaScript Checkbox Validation

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>​
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks

HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form

Categories