Why is disabling form submission affecting min and max attributes? - javascript

I'm doing some validation on a HTML form using min and max attributes. I also want to prevent form submission if the submit button is clicked once to prevent multiple form submissions before a page is reloaded.
Here's the inline code for disabling the button:
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;this.form.submit();">
Here's the number input field code:
<input type="number" name="endNo" placeholder="END" min="5" max="20">
If I include the inline JS for the submit button, the min and max validation doesn't work. When removed, it seems to work just fine. Why is this happening and how can I satisfy both conditions, disable the button once clicked while still validating the min and max values for the number input field?
I'm using google chrome.

The submit method on form element does what it promises, it just submits the form, doesn't do a validation. You can manually do validation with the checkValidity method.
<input type="submit" name="name" value="REGISTER"
onclick="if(this.form.checkValidity()){this.disabled=true;this.form.submit();}">

I'm doing some validation on a HTML form using min and max attributes. I also want to prevent form submission if the submit button is clicked once to prevent multiple form submissions before a page is reloaded.
As you said, you want to prevent form submission, so you must point your bullets to the <form> tag. When you need to handle the submit event, always attack the <form>, so let's add an onsubmit attribute:
<form method="post" action="my-script.php" onsubmit="return something();">
Now let's add a little funtion which tells to our <form> what to do. In this case let's show the result from the input:
<script type="text/javascript">
function something() {
var v = document.getElementById( "endNo" ).value;
alert( "The value is " + v );
return false;
}
</script>
I added some id attribute to the input to be handled by javascript:
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20">
The submit button only shows the disabled event in the onclick attribute because return false is already being executed on the <form> tag:
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;">
The whole tag looks like this:
<script type="text/javascript">
function something() {
var v = document.getElementById( "endNo" ).value;
alert( "The value is " + v );
return false;
}
</script>
<form method="post" action="" onsubmit="return something();">
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20">
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;">
</form>
See it in action: https://jsfiddle.net/darioferrer/mfs3adqm/
Check some similar cases:
On submit form, return false not working
onSubmit after checking return false and still submit
Why does my HTML form still submit when I return false from onsubmit?

It would seem this.form.submit() is bypassing the the min/max checks even if you do it in the console (getting form by id then calling submit). I don't think this has to do with your setup.
Try this approach
<form>
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20" required> <!-- I assume it is required? -->
<input type="button" id="fakeSubmit" name="name" value="REGISTER" onclick="submitIfValid()"> <!-- fake submit -->
<input type="submit" id="submitButton" style="visibility:hidden"> <!-- Actual submit -->
</form>
<script>
function submitIfValid()
{
if(document.getElementById('endNo').value < document.getElementById('endNo').getAttribute("min") || document.getElementById('endNo').value > document.getElementById('endNo').getAttribute("max")) // Get the attributes dynamically and check
{
document.getElementById('submitButton').click(); // Simulate a standard click to show error
}
else
{
document.getElementById('fakeSubmit').disabled = true; // Disabled it, we got our value
document.getElementById('submitButton').click(); // Actual submission
}
}
</script>
Make sure you add your server side checks. NEVER trust jQuery or javascript
Note: If left blank, it would be < than the min
Note 2: If you are open minded towards jQuery, the form validation becomes a lot easier ($(formid).valid()) which makes it easier than my approach and in case of multiple fields to check. You can read about it here.

You could change the input type from submit to button to stop it from submitting right away.
<input type="button" name="name" value="REGISTER" onclick="this.disabled='true';this.form.submit();" />

Related

HTML/JS - Populate a "confirm" popup with a value from an HTML field element

I have the following form fields to collect basic input from the user (a dollar amount).
<tr><td><span class="qText" name="settlement">1. Amount:</span></td></tr>
<td><input type="hidden" class="qAns" name="settlement_t1_a">
<input type="text" class="qAns" id="recovery_val" name="settlement_t1" oninput="formatValue('1');" required></td>
I'm trying to display a confirmation popup when the user clicks the submit button to say "verify amount is correct", and show the amount they entered in the above field "settlement_t1".
What am I doing incorrectly here?
<div class="submitDiv"><input type="submit" onclick="return confirm('Please confirm recovery amount is correct: $' + document.getElementsByName("settlement_t1")[0].value;" value="Submit Form"></div>
Everything works fine until I try to insert the element. As in, I can get it to prompt "Please confirm recovery amount is correct: $", but without the amount.
function doConfirm() {
return confirm('Please confirm recovery amount is correct: $' + document.getElementsByName("settlement_t1")[0].value);
}
function formatValue(value) {
return value;
}
<form method="post">
<input type="hidden" class="qAns" name="settlement_t1_a" />
<input type="text" class="qAns" id="recovery_val" name="settlement_t1" oninput="formatValue('1');" required />
<div class="submitDiv"><input type="submit" onclick="return doConfirm()" value="Submit Form" /></div>
</form>
A big part of the problem is that you are using inline event attributes, which is a 25+ year old legacy approach to event handling that just needs to die but doesn't because people see other people using it and they just copy it. Instead, separate your JavaScript from your HTML and set up events with .addEventListener().
You are also adding a click event handler to a submit button, which triggers the submit event of the form when you should be adding your code to the submit event of the form instead.

How can I submit multiple dynamically generated forms with a single submit button using Javascript? [partial progress]

I am having a bit of trouble with some code. I am attempting to submit multiple forms. The first form is immediately visible, and the second can be added to the page when the user clicks an "Add Another Form" button (think of this like a referral system a user can add multiple referrals to).
So far I am able to submit one form and make more than one form appear on the page, however submitting any more than the first visible form is a challenge. Here is my code so far:
The form (all forms are clones):
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input id="name" type="text">
<input id="phone_number" type="text">
<input id="addanother" type="button" class="formBtn lrgBtn addanother" value="Add Another Form" >
<input type="hidden" name="retURL" value="https://www.example.com/thank-you/">
<input type="button" value="Submit Now" class="loopStarter multiRefHide formBtn" onclick="submitFormLoop()">
</form>
JavaScript for Form Submissions (SubmitFormLoop function):
var formCounter = 0;
var ellipsesCount = 0;
function submitFormLoop(){
if(typeof document.forms[formCounter]!= 'undefined'){
if($('.error:visible').length>0){
return false;
}
document.forms[formCounter].mySubmit.click()
if($('.error:visible').length>0) return false;
$('#submitting').show();
$('#supportCase').hide();
document.getElementById('submittingText').innerHTML = "Submitting your form(s)."
setInterval(function(){
ellipsesCount++;
var dots = new Array(ellipsesCount % 8).join('.');
document.getElementById('submittingText').innerHTML = "Submitting your form(s)" + dots;
}, 300);
setTimeout(function(){submitFormLoop()},1500)
formCounter++
}else{
window.location = "https://example.com/thank-you";
$('input[type="submit"],.addanother').hide()
formCounter = 0;
}
}
Again I can get the first one to submit, but I can't seem to get the function to loop. Any advice on this matter is very welcome, whether it is a small tweak or a recommendation to scrap my code completely.
Thank you all very much.
You cannot submit multiple form elements from the same page.
But you can get the behavior you desire two ways:
Submit the forms using AJAX (using XMLHttpRequest or a helper library like jQuery).
Reformat your inputs to use a single form element.
To do the latter, PHP programmers1 typically use the syntax:
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input name="contacts[0][name]" type="text">
<input name="contacts[0][phone_number]" type="text">
<input name="contacts[1][name]" type="text">
<input name="contacts[1][phone_number]" type="text">
<input name="contacts[2][name]" type="text">
<input name="contacts[2][phone_number]" type="text">
</form>
Notice the [<integer>] in the syntax. In PHP, the $_POST variable will contain data like these as an indexed array.
Your button can then add additional input elements in the same format:
<input name="contacts[3][name]" type="text">
<input name="contacts[3][phone_number]" type="text">
On form submission, you can then retrieve these fields like so:
foreach($_POST['contacts'] as $person){
echo $person['name'];
echo $person['phone_number'];
}
1 I assume you're using PHP since your form's endpoint is submission.php.

Submitting form using button on enter

I have an html form that I want to only submit from a button located outside my form. I am using javascript to perform some verification and do not want the form to submit unless my javascript functions succeed. I found that if I have the button inside the form it will always submit regardless of the javascript, but if I have it outside the form when a user presses enter it simply submits the form. How can I force enter to perform the button javascript instead of submitting?
<form name="form1" action=<?$_SERVER["PHP_SELF"].'?'.$_SERVER["QUERY_STRING"]?> method="post">
<input type="text" maxlength="5" size="5" name="frmZip" value="">
<input type="hidden" name="frmLat" value="200">
<input type="hidden" name="frmLng" value="200">
<input type="submit" disabled="disabled" style="display:none" />
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
EDIT:
Found my solution.
I changed from
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
to
<input type="button" name="frmSubmit" onclick="doClick();" value="Submit">
</form>
This prevented the button from submitting the form so I submitted it in my doClick() via javascript.
EDIT 2:
While this seemed to work for a time, it has stopped catching the enter keystroke. I updated my button to:
<input type="submit" name="frmSubmit" onclick="return doClick();" value="Find Stores">
And always returned false in doClick(). This allowed me to submit the form via javascript once everything had executed.
While this doesn't answer your direct question, you can actually keep the button and simply use your validation on the form submit:
<form onsubmit="return validateForm()">
Then, in your validateForm method, return true or false indicating whether or not the validation has passed.
However to answer your direct question, you can also use the same approach on the submit button which will prevent the form from being submitted.
Update
As pointed out in the comments, an unontrusive solution is often desirable so here's that:
document.getElementById('theForm').onsubmit = function() { return validateForm(); };
Your button inside the form will not submit the form on enter if you add preventDefault...
$("form").submit(function(e) {e.preventDefault();});

How to prevent from refreshing after submitting?

I got this code right here which executes the function validate() when submit is clicked. The function changes some of the text in the page. But I can't see the effect because the page automatically refreshes after submission:
<form name="myForm" onsubmit="validate(); return false;">
Age: <input type="text" name="age" />
Height (meters): <input type="text" name="height" />
Weight (kilograms): <input type="text" name="weight" />
<input type="submit" value="Submit">
</form>
How do I prevent the page from reloading after each submission?
You can use a test button inside your form
<input type="button" value="Test button" onclick="validate();">
Once solved, remove the button.
You can also use Firebug (or equivalent) to add a breakpoint in your javascript code.
The submit event fired by your form automatically initiates the form action. If no form action is declared, it refreshes the page. Your need to prevent this default action from occuring before validation, then submit the data after it has passed validation.
Add preventDefault() to your validation code.
Make sure you add return false; in your validate() function.
That will prevent the form to be submitted.
Example :
function validate() {
//Validation code goes here
return false;
}

How to autosubmit a form in javascript?

I have a form with an input text field which imports data every couple of seconds and display it in the form field , let us say :
<input name="code" id="code" type="text" size="64" maxlength="128" />
and a submit button and my form has the formname form1.
I want the submit button to be clicked as soon as the data in the form field is changed.
I did try to do the following. In the header I did add the follwoing javascript:
<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>
and on the form :
<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />
but it didn`t work..
Any help ?
Thanks
Something like this would work:
<form action="#">
<input type="" id="input" />
<button type="submit"></button:>
</form>
<script>
function send_data() {
document.forms[0].submit();
}
window.onload = function(){
var input = document.getElementById('input');
input.onchange = send_data;
}
</script>
But I'd add a few caveats:
I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using getElementById and referencing that instead of document.forms[x]
The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.

Categories

Resources