I am trying to do a fancy button with some animations to disable it once clicked (or touched on mobile phones). However; I am facing an issue. The issue is that setting the disabled
attribute does complete the animation, but doesn't submit the form. It's working on PCs, though!
<form action="" method="post" enctype="application/x-www-form-urlencoded" role="form">
<div >
<div >
<h2 >Form</h2>
<div >
<input name="id" placeholder="Enter ID" type="text" required>
<label>ID<label>
</div>
<div >
<button type="submit" name="submit" id="submit"
onclick="submitForm();">Search</button>
</div>
</div>
</div>
</form>
function submitForm() {
var submitBtn = document.getElementById("submit");
submitBtn.innerHTML = '<span role="status" aria-hidden="true"></span> Searching...';
submitBtn.setAttribute("disabled", true);
}
What am I missing or is it a bug with Safari on iOS?
EDIT:
Tried ontouchend=submitForm();
but didn't solve the issue.
CodePudding user response:
Edit: simpler answer
Just move your listener/handler from the button's onclick
to the form's onsubmit
.
- This causes your listener/handler to only be invoked after the submit process is invoked, so setting disabled doesn't affect that process.
- This also means you don't need to call
form.submit()
manually - You can then have the original
name="submit"
on the element (although I wouldn't advise it as it overwrites the submit function).
Original answer
This happens because the onclick
event handler occurs before the form is submitted. Subsequently, when it is time to submit the form, the submit input is disabled and so the form should not submit.
Also you have named your button "submit" with name="submit"
. Change the name to something else, like "submitButton" to avoid affecting the native submit
function.
Now you can call submit
in your submitForm handler:
function submitForm() {
var submitBtn = document.getElementById("submit");
submitBtn.innerHTML = '<span role="status" aria-hidden="true"></span> Searching...';
submitBtn.setAttribute("disabled", true);
// calling submit manually
form.submit();
}
Details:
Named inputs of a form are assigned to the object representing the form.
For example, if you have an form named myForm and it has an input named firstName, then firstName can be accessed in JavaScript as such: myForm.firstName
.
Now you have an input called "submit" (the submit button). Guess what's also called submit on the form object? The method that is actually used to actually "submit" your form.
When you have an input called "submit" the method to submit gets overwritten to something completely different and it's no longer pointing to the submit function, hence submit doesn't work no longer.