Find all submit buttons of submitted form - javascript

I'm trying to disable all submit type elements of a form once it's submitted, to avoid double clicking. But I only want the buttons within the submitted form to be disabled.
For example when clicking the Submit button, only the Submit button and the Another submit to disable (same form) should be disabled. The other submit elements should remain as they were.
The code below disables all submit elements.
$(document).on('submit', function (event) {
event.preventDefault();
var submit_button = $(':submit');
submit_button.prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
<input type="text">
<button type="submit">Part of another Form (leave enabled)</button>
</form>
<form>
<input type="text">
<button type="submit">Submit</button>
<button type="submit">Another submit to disable (same form)</button>
</form>

Well, event.target will refer to the submited form, so you can find all submit buttons inside that form using the :submit selector:
$(document).on('submit', function (event) {
event.preventDefault();
$(':submit',event.target).prop('disabled', true);
});
Check the below snippet example
$(document).on('submit', function(event) {
event.preventDefault();
$(':submit', event.target).prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
<input type="text">
<button type="submit">Part of another Form (leave enabled)</button>
</form>
<form>
<input type="text">
<button type="submit">Submit</button>
<button type="submit">Another submit to disable (same form)</button>
</form>

Detect on form submit then search for the button[type=submit] in that form and disable them.
$('form').on('submit', function (event) {
event.preventDefault();
var submit_button = $(this).find('button[type="submit"]');
submit_button.prop('disabled', true);
});

Related

Clarification wanted in the difference between input of type button vs input of type submit when calling jquery form.submit

This code should perform the following when clicked:
submit the form
disable the button to prevent double clicks
add a spinner to the button to notify the user something is happening
if the form is invalid, stop the form submission, remove the spinner, and enable the button.
While writing this code, I found that it will perform validation and form submission only when the button type is set to submit. If the button type is button, the form.submit in the button click event does not submit the form. Processing of the form halts, no validation occurs, no form submission. I set up break points inside the jquery #myForm.submit, and they are never hit. Does anyone have an explanation for this behavior?
frameworks: jquery 3.4.1, bootstrap 4
<form action="doSomething" id="myForm">
...
<!-- this performs validation and submits the form -->
<button type="submit" id="aButton" class="btn btn-primary" data-validate="true">
Save
</button>
<!-- this does not perform validation nor submits the form -->
<button type="button" id="bButton" class="btn btn-primary" data-validate="true">
Save
</button>
</form>
Javascript
removeSpinnerFromButton = function (btn) {
var span = btn.find('span[id="spinner"]');
span.remove();
btn.removeAttr('disabled');
btn.removeClass('cursor-wait');
};
addSpinnerToButton = function (btn) {
btn.attr('disabled', 'disabled');
btn.addClass('cursor-wait');
$("<span/>", {
class: 'spinner-border spinner-border-sm',
id: 'spinner',
role: 'status',
aria_hidden: 'true'
}).appendTo(btn);
};
$('button[data-validate="true"]').click(function () {
var $self = $(this);
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
});
Edit
this bit of code aides in understanding what is happening.
$(function(){
$('#myInputSubmit').click(function(){alert('input of type submit clicked');});
$('#myInputButton').click(function(){alert('input of type button clicked');});
$('#myButtonSubmit').click(function(){alert('button of type submit clicked');});
$('#myButtonButton').click(function(){alert('button of type button clicked');});
$('form').submit(function(e){alert('form submitted');e.preventDefault();});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="button" id="myInputButton" value="input button" />
<input type="submit" id="myInputSubmit" value="input submit" />
<button type="button" id="myButtonButton">button button</button>
<button type="submit" id="myButtonSubmit">button submit</button>
</form>
input or button type="submit" has a default behaviour: Submit the form
button type="button" (or no type at all) doesn't have a default behaviour and you should add it with a listener, as you're already doing for click event. Inside that function you should validate and, if it's the case, submit the form with $('#myForm').submit();, with no params
With this piece of code, you're adding a submit listener to the form instead of submit it:
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
When button is clicked, do your validations and then submit the form. Right now, you need a plugin to validate with $(this).valid(), otherwise, an error will be thrown.
$('button[data-validate="true"]').click(function () {
var $self = $(this);
addSpinnerToButton($self);
if ($(this).valid()) {
$('#myForm').submit();
} else {
removeSpinnerFromButton($self);
}
});

addEventListener redirects to the same page with a '?' at the end of the url

After I click the button or click the send button here's what happens:
HTML super simplified code:
<!DOCTYPE html>
<html>
<body>
<!-- Page Preloder -->
<!-- Header section -->
<header class="header-section">
<form class="header-search-form">
<input id= "searchBarP" type="text" placeholder="Search on divisima ....">
<button id= "searchIconP"><i class="flaticon-search"></i></button>
<script>
var searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
</script>
</form>
</header>
<!-- Header section end -->
</body>
</html>
Here what happens before clicking the button:
After:
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
The first parameter of addEventListener should be an event. You have searchP which is the element. Try putting click instead.
Your button doesn't have a type and the default type, in this case, is "submit". Since you also didn't specify the form's method, it defaults to GET. This method appends all parameters to the URL after a question mark, that's why you see it after clicking the button.
Solution 1:
If you want both the button and the searchbar to perform the same action, listen for the submit event:
<form class="header-search-form" id="form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const form = document.getElementById("form");
form.addEventListener("submit", function(e) {
e.preventDefault();
alert("Trial");
});
</script>
</form>
Solution 2:
Set the button's type to "button" in order to prevent it from submitting the form.
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="button" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP", function() {
alert("Trial");
});
</script>
</form>
Keep in mind, though, that your searchP listener won't work because there's no event called "searchP". If you want to separate the behaviour of clicking the button and hitting "enter" while typing in the search bar, you can do something like this:
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchIconP = document.getElementById("searchIconP");
const searchBarP = document.getElementById("searchBarP");
searchIconP.addEventListener("click", function(e) {
e.preventDefault(); //Remove this if you want to submit the form when you click the button
alert("Button click");
});
searchBarP.addEventListener("keydown", function(e) {
if (e.keyCode === 13){
alert("Search bar enter hit");
e.preventDefault(); //Remove this if you want to submit the form when you hit enter while typing in the search bar
}
});
</script>
</form>

How to validate an html5 form and show error tips on a button click?

I have a button submit inside a form and just a normal button outside of it. I want to validate a form:
function myButtonHandler(evt) {
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
}
This doesn't show the standard error tips inside of input elements when they're invalid when I click on a button -- ones shown by a browser when I click the submit button. How can I get these validation message to pop up when I click on my normal button when the form is invalid?
<form id="my_form">
<input type="text" placeholder="Name" required="true"/>
<input type="submit" id="submit" value="go" />
</form>
No jquery.
You'll need to add the code you've shown to a function that is set up as the click event callback for the normal button:
var myForm = document.querySelector("form"); // reference to form
var btn = document.querySelector("[type='button']"); // reference to normal button
// Set up click event handling function for normal button
btn.addEventListener("click", function(){
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
});
<form>
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="button">Check Validity</button>
If you just want to show the normal browser's validation errors, you can make the second button also a submit button. It's OK for the button to be outside of the form as long as you tie it back to the form with the form attribute.
<form id="theForm">
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="submit" form="theForm">Check Validity</button>

How to prevent submitting search form when search field is empty?

Here the code below disables search button when search box is empty. When input type for search button is set to submit then neither submit nor the enter key from keyboard submits empty form but when I change input type to button and put the cursor inside input field and press enter button even empty form is posted causing reloading of page. How to prevent submitting search form on pressing enter when search field is empty?
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
<script>
$(document).ready(function(){
$('.Button').attr('disabled',true);
$('.search').keyup(function(){
if($(this).val().length !=0)
$('.Button').attr('disabled', false);
else
$('.Button').attr('disabled',true);
})
});
</script>
Add a event listener for the form submission
$('form').submit(function(e){
// check logic here
if ($('.search').val().length < 1)
e.preventDefault()
});
where e.preventDefault will avoid the form being submitted if no value
otherwise the form will submitted normally
here is your code with some modification:
JsFiddle Demo
$(document).ready(function(){
// By default submit is disabled
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
if($(this).val().length !=0 ) {
$('.Button').prop('disabled', false);
} else {
$( ".search").focus();
$('.Button').prop('disabled', true);
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
JsFiddle Demo
You can try like this
$('form').submit(function(e){
if ($('.search').val().length<=0)
return false;
});
you should use prop instead of attr if you want to change disabled
$(function() {
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
$('.Button').prop('disabled', !$(this).val());
});
});

Controlling ENTER key

How can we make a form in a page doesn't submit on pressing Enter — rather. it does the same work as pressing a particular button or icon or image?
Here are the contents of my form:
<input type="text" id="txt" /><input type="button" value="search"
onclick="searchresult()" />
The problem is that if I press Enter, the form submits and text field clears itself but the function searchresult() doesn't show its effect. When only pressing the button, it works well.
HTML
<input type="text" id="txt"/>
<input type="button" value="search"/>
jQuery
$('input[type=text]').on('keyup', function(e) {
if(e.which == 13) { // 13 is keycode for enter
e.preventDefault();
}
})
You can also bind to submit() like following
$('form').submit(function(e) { // instead of only `form`,
// use with `id` or `class` combination
if(e.which == 13) {
e.preventDefault();
}
});
Remainder
Don't forget to place you code within
$(document).ready(function() {
// your code
});
in short
$(function() {
// your code
});
Alternatively, instead of disabling the enter key, you might be able to bind to the onsubmit event to perform any processing prior to submitting the form. From the MDN documentation:
The submit event is raised when the user clicks a submit button in a form ().
Try:
$('form').submit(function(event){
if(!$(':focus',this).is(':button'))
event.preventDefault();
});
This attaches to the form itself. If it was submitted any way other that clicking the submit button it halts the submission process. For better performance narrow down the 'form' selector.
Try this:
form
<form id="myForm">
<input type="text" id="txt" />
<input type="submit" value="search" />
</form>
js
<script>
$(document).ready(function(){
$("#myForm").submit(function(e){
e.preventDefault();
searchresult();
});
});
</script>

Categories

Resources