I got a script that checks every form in my app and if there is one, that gets submitted, it will prevent the submission, toggles a loading screen and then submits the form.
<script>
document.addEventListener('DOMContentLoaded', () => {
const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', (e) => {
e.preventDefault();
document.getElementById('loading').classList.toggle('hidden');
form.submit();
})
});
});
</script>
This works perfectly but for some forms (like a deletion button) I want to ask to user if this is really what he wants to do:
<form method="post" action="<?=base_url('clients/' . $meeting->cid);?>" onsubmit="return confirm('Are you sure?');">
<input type="hidden" name="delmeeting" value="<?=$meeting->id;?>">
<input type="submit" value="Delete" class="button">
</form>
This is in conflict with the first script. The alert gets shown correct but when I cancel it, the first script comes into place and submits.
How can I handle this?
What is important to me:
display the loading div every time for each form
having the possibility to have forms with and without a confirm window
keeping the code small
having individual texts for the confirm
Got it:
const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', (e) => {
if (form.onsubmit === null) {
e.preventDefault();
document.getElementById('loading').classList.toggle('hidden');
form.submit();
}
})
});
``
Related
I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.
I am using a form and a submit button in it to call a post request to server in html
In submit button, I use onclick event to change something in UI before posting request. Everything is fine when I do not change anything to the submit button, it posts request successfully.
But if I change anything in submit button such as value, disable attribute,... then it does not post request
Here is my code
<form action="url"method="post">
<input type="submit" onclick="return onClick(event)">
</form>
js code that does not post request
function onClick(e) {
const submit = e.target // or = this
submit.value = "Clicked"
submit.disabled = true
return true
}
js code that posts request successfully
function onClick(e) {
alert("Clicked")
return true
}
Could somebody tell me the reason why it does not post successfully and how to post with UI change like above?
You need to use submit method to achieve the result.
-> Assign id to the button and form element then get the element like,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
It is always recommended to use addEventListener() method in javascript instead of making it in HTML template.
form.addEventListener('submit', onSubmit)
-> Now you can change the value of an attribute in submit method like,
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
Working snippet as follows,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
form.addEventListener('submit', onSubmit)
<form id="form" action="url" method="post">
<input type="submit" id="btn">
</form>
Whether a form sends a POST or GET request is based on its method attribute. Try changing your form to
<form action="url" method="post">
<input type="submit" onclick="return onClick(event)">
</form>
another solution from me, I found it myself and many thanks to #Maniraj Murugan for your help above: use input type="button" instead, and in onclick event, use form.submit() to submit manually
<form action="url"method="post">
<input type="button" onclick="return onClick(event)">
</form>
and in onClick event
function onSubmit(e){
const btn = e.target
btn.value = "Clicked"
btn.disabled = true
const form = document.getElementById('form')
form.submit()
}
I need to redirect to index.html after clicking on button in a form. I tried this:
$("#btn").on("click", function() {
window.location.replace("index.html");
localeStorage.clear();
})
However in the form I have required inputs, so when I had some empty required input, it redirected, but at the same time it said that I must write something to input.
I need to redirect to index.html after successful form submission. Like on a eshop after submitting an order
Firstly, if you want the form to be validated first before the redirection you need to place the event on the submit of the form, not the click of the button.
Secondly, performing a redirect in JS when the form is submit is redundant; just set the action of the form to where you want the user to be sent.
With the above in mind, try this:
<form id="yourForm" action="index.html">
<input type="text" name="foo" required />
<!-- Some more 'required' form controls... -->
<button type="submit">Submit</button>
</form>
$("#yourForm").on("submit", function() {
localeStorage.clear();
});
what you could do is to verify that the inputs are present before the redirect:
$("#btn").on("click", function() {
// do some checks
//if checks ok call redirect, if ko returns
window.location.replace("index.html");
localeStorage.clear();
})
You can verify the values, use fetch to send the form and then redirect.
( You can add some gestion of server response before redirect. Like "Login already in database ... )
$("#btn").on("click", function() {
const verif = *verifAndFormat(...)* // function that return json like {valid:true , data:... }
if( verif.valid ){
fetch( URL , {method:'POST', body: verif.data} )
.then( resp =>{
/*some operations*/
localeStorage.clear();
window.location.replace("index.html");
})
.catch( err => /*error gestion*/
}else{
/*Invalid value gestion*/
}
})
$(function(){
$('#btn').On('click', function() {
window.location.href="../index.html";
}
}
And also you can call it form html coding on click event to call function submit and redirect from that..
html coding
<input type="button" id="btn" onclick="submit()"/>
Javascript coding
function submit(){
window.location.replace("http://webpagename.index.html");
}
I have a form that submits just fine, but when I add jQuery code to show a loading div using spin.js everything stops working.
<form id="search_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<!-- Form inputs here -->
...
<input id="exam_search" type="submit" name="submit" value="Search" />
Once I add the following code the form stops submitting and nothing happens. The loading div shows for a brief moment and then goes away like expected, but it seems like the form isn't actually submitting anymore.
var opts = // Array of options
var spinner = null;
$("#search_form").submit(function() {
spinner_div = document.getElementById('spinner');
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
} else {
spinner.spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
}
});
If I change all of that code in the submit event to this:
$("#search_form").submit(function() {
alert ("form submitted");
});
It shows the alert and then returns the results of the form submission just fine.
What am I doing wrong here?
EDIT
I saw in the jQuery docs for submit() that I shouldn't use the name "submit" on the input field. I tried changing that as well with no luck.
Well I'm not sure why but simply doing this worked:
$("#search_form").submit(function() {
var spinner_div = document.getElementById('spinner');
var spinner = new Spinner(opts);
spinner.spin(spinner_div);
});
I have a submmit button like Following:
Save & Continue
And My function in js is:
function checkCreditDebit(buttonValues) {
//Some validation here
//Disable Button if once clicked to prevent twice form submission
document.getElementById('saveandcontinue').disabled = 'disabled';
document.getElementById('onlysave').disabled = 'disabled';
}
But when i submit form in firefox it disabled the "save & continue", button and submit form. But in chrome it disable the button but not submit the form. What is the wrong with this please suggest. Thanks in Advance
Instead of just disabling your submit button(forms can also be submitted if you press enter on text-boxes), attach a handler to your form that will leave a 'class name' to your form as a mark that the form was already submitted, if the user submit the form again, the handler should check if the form has already the class name, then prevent duplicate submission via event.preventDefault().
try this:
<form onsubmit="prevent_duplicate(event,this);" action="">
<input type="text" />
<input type="submit" />
</form>
<script>
function prevent_duplicate(event,form)
{
if((" "+form.className+" ").indexOf(" submitted ") > -1)
{
alert("can't submit more than once!!!");
event.preventDefault();
}
else
{
form.classList.add("submitted");
}
}
</script>
Demo here
instead of disabling pervent multiple submit by setting a javascript flag example :
<form method="post" id="ecomFormBean" name="ecomFormBean" onsubmit="return checkSubmit(this);" >
<input type="text" />
<input type="submit" />
</form>
<script>
var formSubmitted = false;
function checkSubmit(f){
if (formSubmitted) {
alert('Please be patient. Your order may take 10 - 15 seconds to process. Thank you!');
return false;
}
else return formSubmitted = true;
}
</script>
Chrome runs javascript very fast. So it might be possible your checkCreditDebit(buttonValues) function which is to disable submit button executes before your php script submits the form.
I suggest you to call setTimeOut function before calling the javascript function so that the form can get submitted.
Give it a try.