I have a form with multiple submit buttons, and I'd like to capture when any of them are pressed, and perform different JS code for each one.
<form id="my-form">
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
Looking at an older answer, I can process all of the submit buttons in JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?
I don't need to have three submit buttons, per se... I just need three different buttons in a form to perform three different actions.
Thanks!
you can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:
Live Example
$("#my-form button").click(function(ev){
ev.preventDefault()// cancel form submission
if($(this).attr("value")=="button-one"){
//do button 1 thing
}
// $("#my-form").submit(); if you want to submit the form
});
use this
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
var submit_type = document.getElementById('my-form').getAttribute("value");
if(submit_type=="button-one"){
}//and so on
// You must return false to prevent the default form behavior
return false;
}
HTML:
<form id = "form" onSubmit = {handleSubmit}>
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
JS:
const handleSubmit = e => {
e.preventDefault();
var ans = document.activeElement['value'];
console.log(ans);
};
You can also use the read-only submitter property of a SubmitEvent.
HTML (same as you have):
<form id="my-form">
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
JS:
let form = document.getElementById("my-form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault()
alert(event.submitter.value) // shows a different value depending on button pressed
From there on, it's easy to use submitter as a control flow, e.g.:
let form = document.getElementById("my-form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault()
submitter = event.submitter.value
switch (submitter) {
case "button-one":
alert(1)
break;
case "button-two":
alert(2)
break;
case "button-three":
alert(3)
break;
}
}
But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?
Yes, you can use querySelector to grab elements with attributes.
document.querySelector('#my-form button[value="button-one"]' )
Related
I am trying to reset the form to blank values in the input textboxes after the data filled in the textbox have been searched.
<form id="myForm" class="mt-5" asp-controller="Leave" asp-action="GetAllLeaves">
<div class="form group col-md-6">
<label>Employee </label>
<div class="col">
<input type="hidden" id="employeeId" name="employeeId" />
<input type="text" name="employeeName" id="employeeName" value="#ViewData["CurrentFilterE"]" />
</div>
</div>
<button type="submit" class="btn btn-outline-success">Search</button>
<button type="reset" id="reset" class="btn btn-outline-primary">Reset</button>
</form>
I have tried bunch of different javascripts but none of them work after the search has been completed. They work fine before the search button is clicked. I am aware that there are questions already asked about this here and I have tried those codes but they don't work for me.
These are the different codes that I have tried. They don't work after the search button has been hit. Even refreshing the page does not delete the data in the input boxes.
function myFunction() {
document.getElementById("myForm")[0].reset();
};
$("#reset").click(function () {
$(this).closest('form').find("input[type=text], textarea").val("");
});
document.getElementById("reset").onclick = () => {
document.getElementById("myForm").reset()
};
let inputs = document.querySelectorAll('input');
document.getElementById("reset").onclick = () => {
inputs.forEach(input => input.value ='');
}
in your post method you need to have an IactionResult return type method and then you need to pass property name to ModelState.Remove method, not the value.
Either pass the property name in string, eg. ModelState.Remove("PropertyName"); or in the newer .NET framework, you can use nameof() keyword, eg. ModelState.Remove(nameof(model.Property));
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset.
Your default input value = "#ViewData["CurrentFilterE"]". Reset method restores a form element's default values.
This will help to reset the input:
html:
<form id="myForm">
<input type="text" name="employeeName" id="employeeName" value="test" />
<button id="reset" class="btn btn-outline-primary">Reset</button>
</form>
js:
document.getElementById("reset").onclick = function(e) {
document.getElementById("employeeName").value = "";
}
I ended up using the following
$("#reset").click(function () {
// this for normal <input> text box
$('#employeeName').attr("value", "");
//this for checkbox
document.getElementById('searchAprroved').removeAttribute('checked');
});
I have a simple function that intercepts a form submit event, displays a SweetAlert2 confirmation dialogue, and if the user confirms the form is submitted.
The function is something like this:
$(document).ready(function() {
$('form.require-confirmation').submit(event => window.swalConfirm(event));
});
window.swalConfirm = function(e)
{
e.preventDefault();
Swal.fire().then((result) => {
if (result.value) {
e.target.submit();
}
})
};
This works as expected… in most cases. When the form has multiple submit buttons – for example:
<button type="submit" name="action" value="add">Add</button>
<button type="submit" name="action" value="remove">Remove</button>
… the value of "action" is removed from the submitted form. Is there any way around this, like resuming the initial submit or something like that? Or is there no option but making the buttons change the value of a hidden input before submitting the form, for example?
You gave the solution yourself
<input type="hidden" name="action" value="" />
<button type="button" class="action" value="add">Add</button>
<button type="button" class="action" value="remove">Remove</button>
$(function() {
$('.action').on("click",function(e) {
const parent = this.form;
$("[name=action]").val(this.value);
Swal.fire().then((result) => {
if (result.value) {
parent.submit();
}
})
});
});
I have the following code:
<form id="buttonForm" action = "/goSomeWhere" method="post" >
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" value="Previous Page" >
</form>
When either one of this two buttons are submitted I receive "bnext" or "bprevious" values in Django View request.POST so I can further construct the logic that I need.
But when I'm trying to insert some javascript for the second button I loose those values:
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" id="bpid" onclick="disable()" value="Previous Page" >
function disable()
{
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").submit();
}
There is a way to do this and still receiving input names values ?
Sorry I didn't fully understood that what you are trying to do
If you are trying to stop form submission then:
function disable() {
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").preventDefault();
}
If you want that client should not click previous button again then, it is best to change inputType submit to hidden:
function disable() {
document.getElementById("bpid").type="hidden";
document.getElementById("buttonForm").submit();
}
Or
create new <input type=hidden>, set name values ,append to form and submit it:
function disable() {
document.getElementById("bpid"). disabled=true;
newip= document.createElement("input");
newip.type="hidden";
newip.name="bprevious";
newip.value="Previous Page";
document.getElementById("buttonForm").appendChild(newip);
document.getElementById("buttonForm").submit();
}
try to use button instead input like this
<button name="bprevious" id='bpid' onclick='disable()' value="Previous Page">Previous Page</button>
Let's say I have this HTML:
<div id="container"></div>
<p>Output: <span id="output"></span></p>
and this JS:
function otherAction(e) {
document.getElementById('output').innerHTML = 'otherAction';
e.preventDefault();
}
function submit(e) {
document.getElementById('output').innerHTML = 'submit';
e.preventDefault();
}
ReactDOM.render(
<form onSubmit={submit}>
<input type="text" defaultValue="foo" />
<button onClick={otherAction}>Other Action</button>
<button type="submit">Submit</button>
</form>,
document.getElementById('container')
);
Actually, let's not just say it, let's put it in a JSFiddle example. What I want to happen is that:
Clicking the "Other Action" button triggers the otherAction function (it does!)
Clicking the "Submit" button triggers the submit function (it does!)
Putting your cursor in the text box and pressing enter triggers the submit function (this does not work currently!)
In #3, what happens instead is that otherAction gets triggered. How can I change that?
If you set the first button to type="button" (i.e. provide a type for each button) it should work.
<button type="button" onClick={otherAction}>Other Action</button>
https://jsfiddle.net/L0urqamz/3/
You should provide types for all buttons, otherwise it won't work:
<form onSubmit={handleSubmit}>
// form content
<button type="button" onClick={someButtonEvent}>DO STH</button>
<button type="submit">SUBMIT</button>
</form>
<script>
function disableButton() {
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
<form class="form-horizontal" name ="reg" method="post" action="" onSubmit="return disableButton()"/>
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button
When I hit submit button button is disbled but form is not submitted
Kindly any one please do favour
Instead of trying to add functions to your forms, you can simply catch your form submit, disable the button and allow it continue afterwards:
HTML Part:
<form class="form-horizontal" id="reg" name="reg" method="post" action="" />
Javascript Part:
<script type="text/javascript">
var form = document.getElementById('reg');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
function processForm(e) {
if (e.preventDefault) e.preventDefault();
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
If you wish to test it out, change above to return false;. This will disable the form submit and only disable the button.
Try the following:
<?php echo "<pre>";var_dump($_POST); echo "</pre>";?>
<script>
function disableSubmit() {
var button = document.getElementById('accept');
button.disabled = true;
myNiceForm.submit();
}
</script>
<form class="form-horizontal" id="myNiceForm" name ="reg" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="myTestText"/>
<input id="accept" type="submit" onclick="disableButton()"/>
</form>
Things to consider:
If you want your HTML form to be posted, it needs to have a proper
value for the action attribute.
The button with the id of accept doesn't cause the form to be
posted, you also don't have any client-side script to do so, and it's
not a good practice, so a submit button has been added to the form.
When you click the submit button, the disableSubmit() function
invokes, and disables the button, and finally submits the form
programmatically, however, it's not necessary.
Your function does not follow proper syntax. But other than that there's no real reason to return true or false...
var acceptor = document.getElementById("accept");
acceptor.addEventListener("click", toggleButton);
function toggleButton() {
acceptor.disabled = "disabled"
}
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button>
Also, your button tag is not closed <button> </button>...
You can simply define the attribute are defined as a boolean true or false, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled".
You may want to consider a function buttonToggler... so you can later switch it back easily (although I'm not sure this will help you...
Also... have the script at the bottom of the body rather than the top in-case of a preloading issue (this is not a foolproof solution to the problem where the JS loads faster than the HTML).
<script type="text/javascript">
function toggleButton() {
var acceptor = document.getElementById('accept');
if acceptor.disabled === true{
acceptor.disabled=false;
} else {
acceptor.setAttribute('disabled', 'disabled');
}
</script>
Try that.