How to automatically submit form when browser autofills the input values - html

I have this form:
<form method="post">
<input type="tel" name=phone_no required>
<input type="password" name=password required>
<button type="submit">Sign In</button>
</form>
How can I automatically submit this form when browser auto-fills these input fields in form ?

You can do this using Javascript :
(1) Get html elements with selector :
document.getElementsByName(..)
(2) Check if the elements contains any value.
element.value
(3) In that case, trigger an event which click on the submit button :
button.click();

Related

Adding additional string to an existing value in a HTML form's input box before submission

I have a form with an input box and I want to change the value before submit.
Example:
<form action="savefiends.php" method="post">
<input type="text" name="id" value="123456"><br>
<input type="submit">
</form>
How can I save the value as 123456#example.com without editing savefiends.php?
P.S. user can edit the value
You can use the onsubmit attribute as shown in the snippet below.
Note: I added extra checking to avoid appending "#example.com" if already present. Also I replaced the action attribute content by "#" to avoid form submission.
function resetId(){
var idInput = document.getElementById("id");
var suffix="#example.com";
// just to check if #example.com is already present
var checkRegExp=new RegExp(suffix + "$");
if (!idInput.value.match(checkRegExp)) idInput.value +="#example.com";
alert("Value before submit:" + idInput.value);
}
<form action="#" method="post" onsubmit="resetId();return false">
<input type="text" name="id" value="123456" id="id"><br>
<input type="submit">
</form>

how do i make my required textfield work first and then the onclick

<input class="form-control" type="text" name="txtSpouseOccupation" id="txtSpouseOccupation" required>
<button type="button" id="next_personal" class="form-control btn-success" style="width:10%" onclick="openTab(event,'dependentTab')">Next</button>
when I click the next button it just goes to the next tab and ignores the required even the inputs are not yet filled up
You can accomplish your need by using this simple attribute required. So below I'll add example;
<html>
<head>
</head>
<body>
<form action="next.php">
<input type="text" required="true">
<input type="submit">
</form>
</body>
</html>
So when you click button to navigate to next page or tab it will show simple message near relevant text box to fill that field.
Though you used tabs you can use this.
In this case, your both elements are independent to each other. You have text/input whose functionality is to take inputs and then there is a submit button whose functionality to do something on click.
Now required will only work if you define a relation between submit button and input/text. <form> elements does that for you as it wraps both elements in it and than the submit button default action is to submit the form, and then before submitting it will check if the input values are assigned as per required=true.
But you trigger a function on the click of it. If you simply want to go to some url by submitting form
Try Form
<form action="your url" method="GET or POST">
<input type= "text" required ="true"/>
<button type = "submit" >next</button>
</form>
OR you can use javascript for it.
function newTab(){
let input = document.getElementById('text-input').value;
if(input === ""){
alert('please fill text')
return;
}
window.location.href = 'http://google.com';
}
<input type= "text" required ="true" id = "text-input"/>
<button type = "submit" onClick = "newTab()" >next</button>

How to disable messages from of HTML validation but keep validation enabled

I need to disable only the error message of HTML Validation; the actual validation should still be there. User won't submitted the form without filling text field. Even if the user does not fill in a required text field, I don't want to display any message like "Please fill out this field".
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="" required>
<br>
<input type="submit" value="Submit">
</form>
You can use novalidate attribute to skip validation from HTML and then add validation code on javascript - on submit event.
HTML:
<form novaidate>
First name:<br>
<input type="text" name="firstname" value="" required>
<br>
<input type="submit" value="Submit">
</form>
JS:
$('form').submit(function(){
//check validations and submit through AJAX
return false;
});

HTML5 validation when the input type is not "submit"

I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

Two submit buttons in one form

I have two submit buttons in a form. How do I determine which one was hit serverside?
Solution 1:
Give each input a different value and keep the same name:
<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />
Then in the code check to see which was triggered:
if ($_POST['action'] == 'Update') {
//action for update here
} else if ($_POST['action'] == 'Delete') {
//action for delete
} else {
//invalid action!
}
The problem with that is you tie your logic to the user-visible text within the input.
Solution 2:
Give each one a unique name and check the $_POST for the existence of that input:
<input type="submit" name="update_button" value="Update" />
<input type="submit" name="delete_button" value="Delete" />
And in the code:
if (isset($_POST['update_button'])) {
//update action
} else if (isset($_POST['delete_button'])) {
//delete action
} else {
//no button pressed
}
If you give each one a name, the clicked one will be sent through as any other input.
<input type="submit" name="button_1" value="Click me">
There’s a new HTML5 approach to this, the formaction attribute:
<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>
Apparently this does not work in Internet Explorer 9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).
Personally, I generally use JavaScript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are Internet Explorer before version 9 with JavaScript disabled.
Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.
As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.
An even better solution consists of using button tags to submit the form:
<form>
...
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).
This is extremely easy to test:
<form action="" method="get">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
Just put that in an HTML page, click the buttons, and look at the URL.
Use the formaction HTML attribute (5th line):
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<button type="submit">Submit</button><br>
<button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>
<form>
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
The best way to deal with multiple submit buttons is using a switch case in the server script
<form action="demo_form.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">JavaScript</button>
<button name="subject" type="submit" value="jquery">jQuery</button>
</form>
Server code/server script - where you are submitting the form:
File demo_form.php
<?php
switch($_REQUEST['subject']) {
case 'html': // Action for HTML here
break;
case 'css': // Action for CSS here
break;
case 'javascript': // Action for JavaScript here
break;
case 'jquery': // Action for jQuery here
break;
}
?>
Source: W3Schools.com
Maybe the suggested solutions here worked in 2009, but I’ve tested all of this upvoted answers and nobody is working in any browsers.
The only solution I found working was this (but it's a bit ugly to use I think):
<form method="post" name="form">
<input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
<input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>
</form>
You formaction for multiple submit buttons in one form
example:
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress">
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress">
An HTML example to send a different form action on different button clicks:
<form action="/login" method="POST">
<input type="text" name="username" value="your_username" />
<input type="password" name="password" value="your_password" />
<button type="submit">Login</button>
<button type="submit" formaction="/users" formmethod="POST">Add User</button>
</form>
The same form is being used to add a new user and login user.
Define name as array.
<form action='' method=POST>
(...) some input fields (...)
<input type=submit name=submit[save] value=Save>
<input type=submit name=submit[delete] value=Delete>
</form>
Example server code (PHP):
if (isset($_POST["submit"])) {
$sub = $_POST["submit"];
if (isset($sub["save"])) {
// Save something;
} elseif (isset($sub["delete"])) {
// Delete something
}
}
elseif very important, because both will be parsed if not.
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):
<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>
Rather than using the value to determine which button was pressed, you can use the name (with the <button> tag instead of <input>). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL.
In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:
if "register" in kwargs:
pass # Do the register code
elif "login" in kwargs:
pass # Do the login code
<form method="post">
<input type="hidden" name="id" value="'.$id.'" readonly="readonly"/>'; // Any value to post PHP
<input type='submit' name='update' value='update' formAction='updateCars.php'/>
<input type='submit' name='delete' value='delete' formAction='sqlDelete.php'/>
</form>
I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked won't appear in that list.
You can also do it like this (I think it's very convenient if you have N inputs).
<input type="submit" name="row[456]" value="something">
<input type="submit" name="row[123]" value="something">
<input type="submit" name="row[789]" value="something">
A common use case would be using different ids from a database for each button, so you could later know in the server which row was clicked.
In the server side (PHP in this example) you can read "row" as an array to get the id.
$_POST['row'] will be an array with just one element, in the form [ id => value ] (for example: [ '123' => 'something' ]).
So, in order to get the clicked id, you do:
$index = key($_POST['row']);
key
As a note, if you have multiple submit buttons and you hit return (ENTER key), on the keyboard the default button value would be of the first button on the DOM.
Example:
<form>
<input type="text" name="foo" value="bar">
<button type="submit" name="operation" value="val-1">Operation #1</button>
<button type="submit" name="operation" value="val-2">Operation #2</button>
</form>
If you hit ENTER on this form, the following parameters will be sent:
foo=bar&operation=val-1
The updated answer is to use the button with formaction and formtarget
In this example, the first button launches a different url /preview in a new tab. The other three use the action specified in the form tag.
<button type='submit' class='large' id='btnpreview' name='btnsubmit' value='Preview' formaction='/preview' formtarget='blank' >Preview</button>
<button type='submit' class='large' id='btnsave' name='btnsubmit' value='Save' >Save</button>
<button type='submit' class='large' id='btnreset' name='btnsubmit' value='Reset' >Reset</button>
<button type='submit' class='large' id='btncancel' name='btnsubmit' value='Cancel' >Cancel</button>
Full documentation is here
In HTML5, you can use formaction & formmethod attributes in the input field
<form action="/addimage" method="POST">
<button>Add image</button>
<button formaction="/home" formmethod="get">Cancel</button>
<button formaction="/logout" formmethod="post">Logout</button>
</form>
You can also use a href attribute and send a get with the value appended for each button. But the form wouldn't be required then
href="/SubmitForm?action=delete"
href="/SubmitForm?action=save"
You can present the buttons like this:
<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">
And then in the code you can get the value using:
if request.method == 'POST':
#valUnits = request.POST.get('unitsInput','')
#valPrice = request.POST.get('priceInput','')
valType = request.POST.get('typeBtn','')
(valUnits and valPrice are some other values I extract from the form that I left in for illustration)
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for PHP
<?php
if(isset($_POST["loginForm"]))
{
print_r ($_POST); // FOR Showing POST DATA
}
elseif(isset($_POST["registrationForm"]))
{
print_r ($_POST);
}
elseif(isset($_POST["saveForm"]))
{
print_r ($_POST);
}
else{
}
?>
<html>
<head>
</head>
<body>
<fieldset>
<legend>FORM-1 with 2 buttons</legend>
<form method="post" >
<input type="text" name="loginname" value ="ABC" >
<!--Always use type="password" for password -->
<input type="text" name="loginpassword" value ="abc123" >
<input type="submit" name="loginForm" value="Login"><!--SUBMIT Button 1 -->
<input type="submit" name="saveForm" value="Save"> <!--SUBMIT Button 2 -->
</form>
</fieldset>
<fieldset>
<legend>FORM-2 with 1 button</legend>
<form method="post" >
<input type="text" name="registrationname" value ="XYZ" >
<!--Always use type="password" for password -->
<input type="text" name="registrationpassword" value ="xyz123" >
<input type="submit" name="registrationForm" value="Register"> <!--SUBMIT Button 3 -->
</form>
</fieldset>
</body>
</html>
Forms
When click on Login -> loginForm
When click on Save -> saveForm
When click on Register -> registrationForm
Simple. You can change the action of form on different submit buttons click.
Try this in document.Ready:
$(".acceptOffer").click(function () {
$("form").attr("action", "/Managers/SubdomainTransactions");
});
$(".declineOffer").click(function () {
$("form").attr("action", "/Sales/SubdomainTransactions");
});