Form html, type submit - javascript

I'm building one cordova application that uses one tag form with a submit button, the problem is that this is one mobile application, so when a click on my text input, write something and than click on confirm button of my mobile keyboard, my problem happens. Because when I click on this button, I want to move to the next input, but my aplication execute my submit method. What I have to do to my application pass to the next input and if, and only if this is my last input, so verify if all input are filled.
This is my html code:
<form id="form">
<label for="idNome"> Nome: </label> <input name="nome" id="idNome"
placeholder="Seu Nome" required autofocus autocomplete="on"><br>
<label for="idCpf"> CPF:</label> <input type="tel"
autocomplete="on" name="cpf" id="idCpf" placeholder="Seu CPF"
required> <img style="display: none;" id="idValidadeCPF"
src=""><br>
<label for="idEndereco"> Endereço:</label>
<textarea id="idEndereco" rows="1" cols="30"></textarea><br>
<label for="idMensagem"> Mensagem: </label><br>
<textarea cols=30 id="idMensagem" rows="10" name="mensagem"
maxlength="500" wrap="hard"
placeholder="Informe datalhes sobre o seu problema." required></textarea><br>
<input type="submit" value="Enviar" onclick="submitForm()" />
And this is my submitForm method
function submitForm(){
document.getElementById('form').onsubmit= function(e){
e.preventDefault();
alert("Todos os campos devem ser preenchidos");
}
}

Your submitForm() function isn't actually doing the logic it contains, it's just setting a handler. It's basically just doing this:
document.getElementById('form').onsubmit = someFunction;
And that's all. Whatever's inside of someFunction isn't going to be executed until the next time the handler is invoked. But it sounds like you want it invoked right away.
Instead of assigning the submit handler when you submit the form, assign it right away when the page loads. Something like this:
<form id="form">
... your form
<input type="submit" value="Enviar" />
</form>
<script type="text/javascript">
document.getElementById('form').onsubmit = function(e){
e.preventDefault();
alert("Todos os campos devem ser preenchidos");
}
</script>
Notice that I've removed the submitForm function entirely, as well as removed it from the input which was calling it. It isn't really needed in this case. That input is of type submit so it will submit the form by default. But when the page loads this JavaScript adds your anonymous function as the handler for the form's submit event, so this function will run when the input submits the form.
It's worth noting that this will prevent the form from ever actually being submitted, though. You're only submit handler prevents the default action (submitting the form) and shows an alert(). It's not clear to me why you're doing that or what you're trying to accomplish.

Related

Send form with both triggers for action and onclick

I need to connect one button to 2 activities, in this case the form argument "action" and button argument "onclick" inside a form.
The forms "action" is PHP-based class and the button's "onclick" is connected to a javascript.
Environment:
The question is generic but to clarify I will use the form in later stage in a Laravel 8 environment. This means that the handling of form "action" is being taken care of by Laravel through a route. The onclick should be triggered and the javascript is physically positioned at the end of the Laravel blade view.
The problem:
I noticed that having the button inside the form, runs the form "action", but prevents the button argument "onclick" to trigger the javascript. If put the mentioned button outside of form, then one can trigger the form, and the button outside the form but ends up with need of 2 buttons which break simplifying the user flow.
Question:
How can I trigger both form "action" and the javascript function from one button? Note! It is not needed that javascript is being trigger by "onclick" if there are other ways to trigger the javascript.
Test-1: Basic form
<form
method="post"
action="/payment-checkout"
>
<button type="button" name="button" onclick="initCheckout()">Send</button>
</form>
Result test-1:
forms action is being executed, but not javascript.
Test-2: Attempt to solve problem using form attribute "onsubmit":
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
// Execute this...
}
document.getElementById("myForm").onsubmit = function() {submitFormFromJavascriptFunction()};
Result test-2:
forms action is being executed, but not javascript.
Try to trigger sumbit event on a button click manually by using
document.getElementById("myForm").submit();
from your onclick function
Example
function submitform() {
console.log('Inside the onclick function');
document.getElementById("myForm").submit();
}
<form action="/action_page.php" id="myForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<button type="button" onclick="submitform()">Submit</button>
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>
Below is an example of doing a conventional html form submit with javascript execution on submit of the form.
The form gets submitted based on the return value of the javascript function.
Javascript function is attached to onsubmit event of the form.
button is a normal submit button with no event handler attached to itself.
//this function getts called on submission of the form via submit button.
//Its return value dictates whether form will be submitted or not
function checkQuery(){
var query = document.getElementById('myQuery');
if(query.value==""){
alert("Please enter your search query")
return false; //form will not submit
}
return true;//form will get submitted and laravel will see that submit button was pressed
}
<form
method="get"
action="https://stackoverflow.com/search" onsubmit="return checkQuery();"
>
<input type="text" id="myQuery" name="q" placeholder="your search query here">
<button type="submit" name="button">Search Now</button>
</form>
Your Test 2 should be like this:
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="return submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
console.log("submitFormFromJavascriptFunction is getting called");
return true // or false based on your logic
}
// no need for below line
//document.getElementById("myForm").onsubmit = function() //{submitFormFromJavascriptFunction()};

Alert blocking "required field" pop-up

I am making a form that when filled out is creates an alert telling you that it was a success and where the user is about to be redirected to. The problem is that this alert seems to be "blocking" the chrome "please fill out this field" pop-up for input fields with the required attribute that were not filled in.
It is (to my knowledge) only an Chrome problem. IE still shows the pop-up after the alert, and I have not been able to try Firefox.
For example
<form method="post" action="sendemail.php">
<input type="text" name="name" required>
<input type="submit" name="submit" onclick="javascript:alert('All done')">
</form>
The best result would be to only show the alert if all the required fields are filled in.
Simply remove the onclick and add onsubmit to the form tag:
<form method="post" action="sendemail.php" onsubmit="javascript:alert('All done')">
<input type="text" name="name" required/>
<input type="submit" name="submit"/>
</form>
onsubmit only fires once the form is submitted, which won't happen if a required input isn't filled in. onclick always fires when clicking the submit button, even if all fields aren't correct.

Why is disabling form submission affecting min and max attributes?

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();" />

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;
}

Categories

Resources