HTML5 required attribute trigger action with jQuery - javascript

I'm working on a prototype and I want to trigger an action after a submit but only if the required fields were filled.
I have this code
<button type="submit" onclick="doSomething()" class="btn btn-primary">Register</button>
And also an input on my form using the 'required' attribute from HTML 5, like this
<input type="text" class="form-control" placeholder="Name" required>
I want to trigger the action onclick only if the input was filled.
I suppose I could do this by checking if the input was filled using jQuery, I was wondering if there is a simpler way

Well, I have actually found a solution, if anyone is going through the same problem, this is how I did it.
Instead of using "onclick" on the button tag I added an "onsubmit" (I had no clue this existed) event inside my form tag with my doSomething function, like this:
<form onsubmit="doSomething()">
The function will only be called if the required inputs are filled, easy as that.
Thanks for the ones who tried to help anyway

Try using oninput event
function doSomething() {
console.log("do stuff")
}
document.querySelector("input").oninput = function() {
this.nextElementSibling.click()
}
<input type="text" class="form-control" placeholder="Name" required>
<button type="submit" onclick="doSomething()" class="btn btn-primary">Register</button>

Well you can always use this https://jsfiddle.net/2Lzo9vfc/26/
HTML
<button type="submit" class="btn btn-primary">Register</button>
<input type="text" class="form-control" placeholder="Name" required>
JS
$('button').click(function() {
var content = $('input').val();
if(content != '') {
alert(content);
}
});

Related

i am using required html tag for input fields but its not working [duplicate]

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>

Find class inside form validation function

Why I am doing it
I have used jquery validation plugin but it doesn't show desired output when used with bootstrap select. Hence trying to create my own optional method.
What I want to do
I want to search the form called by FormValidation function for specific class name across all inputs, select, checkboxes & radio buttons. If class found then I'll do some validation for quality & values & if validation fails then I would include error class after that element only.
I am here to get some help on searching the form called by FormValidation function for specific class name only
What I have tried
I have tried searching classname using following but it's not searching as desired.
function FormValidation()
{
if($(this).hasClass( "fns" ))
{
//do some validations & show validation output
}
}
I also tried to get form id so that I can search elements of form by form id using $(this).closest("form").attr("id"); but this is showing undefined.
Please tell me what wrong I am doing here.
<form method="post" class="form-horizontal" id="EMPREG" onSubmit="return FormValidation();" onKeyUp="return FormValidation();">
<input class="form-control fns" type="text" id="Rec_Name" name="Rec_Name" placeholder="Enter Your Name">
<input type="submit" name="Create_Profile" id="Create_Profile" class="btn btn-success btn-md" value="Create Profile"/>
</form>
Js Fiddle for reference https://jsfiddle.net/ttt/cc3r36h0/
The this keyword in your function refers to widow global object.
If you need to code inline events try to pass the this, and event keywords:
<form method="post" class="form-horizontal" id="EMPREG" onSubmit="return FormValidation(this, event);"
onKeyUp="return FormValidation(this, event);">
<input class="form-control fns" type="text" id="Rec_Name" name="Rec_Name" placeholder="Enter Your Name">
<input type="submit" name="Create_Profile" id="Create_Profile" class="btn btn-success btn-md"value="Create Profile"/>
</form>
So your function will be:
function FormValidation(obj, evt)
{
if($(obj).find(".fns").length > 0)
{
//do some validations & show validation output
}
}

How to make form submit different button when I press enter on different text input?

For example, I have this form:
<form action="destination.jsp" method="POST">
<input type="text" name="Productqty1"/>
<input type="text" name="Productqty2"/>
<input type="text" name="Productqty3"/>
<input type="submit" name="RecalculatePrice" value="Recalculate Price"/>
<input type="text" name="ZipCode"/>
<input type="submit" name="RecalculateShipping" value="Recalculate Shipping"/>
<input type="text" name="Offercode"/>
<input type="submit" name="RecalculateDisc" value="Recalculate Discount"/>
<input type="submit" name="CheckOut"/>
</form>
I need that if the user press enter on Productqty1, Productqty2, or Productqty3, then the default action is suppressed, and button RecalculatePrice is clicked instead.
And the same goes with if user press enter on ZipCode, the RecalculateShipping button gets clicked instead. The same with Offercode input and RecalculateOffercode button.
But if the user press on CheckOut button, the whole form must be still submitted. That's why they're on the same form, multiple submit button on the same form.
I also need to suppress the default action of enter key, because IE8 did not sent button submit value along with the form submit, so let's disable it altogether to avoid confusion.
How can I find a unified solution for this? It's okay if it has to be made in multiple javascript function, just as long as I can understand the solution pattern, because form with multiple submit button and user can press enter on any input field is confusing me. JQuery solutions are welcomed. Thanks.
EDIT: sorry for the poor choice of words that lead to confusion. What I mean with suppress default action is that when you press enter, the form get submitted, using any (random?) button submit. That is the default behavior I want to suppress.
I have added classes and id for each submit button(added id) and text box(added class).
Try this
<form action="destination.jsp" method="POST">
<input type="text" name="Productqty1" class="class1"/>
<input type="text" name="Productqty2" class="class1"/>
<input type="text" name="Productqty3" class="class1"/>
<input type="submit" name="RecalculatePrice" value="Recalculate Price" id="class1"/>
<input type="text" name="ZipCode" class="class2"/>
<input type="submit" name="RecalculateShipping" value="Recalculate Shipping" id="class2"/>
<br><br>
<input type="text" name="Offercode" class="class3"/>
<input type="submit" name="RecalculateDisc" value="Recalculate Discount" id="class3"/>
<input type="submit" name="CheckOut"/>
</form>
Script
$(document).ready(function () {
$(".class1").keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
$('#class1').click();
}
});
$(".class2").keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
$('#class2').click();
}
});
$(".class3").keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
$('#class3').click();
}
});
});
Fiddle Demo
I would argue that CheckOut is your special scenario here. While you could certainly catch the enter key and invoke different actions, there are primarily two reasons why I don't find that to be the optimal solution here:
Your IE8 concern seems to negate the entire prior discussion, and in my mind, this should advise you to look in another direction. Don't do a special solution for IE8, do something that all supported browsers can understand.
There is no field for which CheckOut should be the default action on enter.
I suggest that you make different forms, and use different actions, rather than checking which button was clicked by inspecting the name parameter of the button.
On click of the CheckOut-button, which should never be triggered by an enter key, you should submit all forms. You can serialize their combined values and post them like so:
$('#product-form, #zip-form, #offer-form').serialize();
You can use jquery/javascript function to change the form.action before submitting the page.
Submit type should submit the form to default form action, which has been added on form declaration.
<form action="destination.jsp" method="POST">
<input type="text" name="Productqty1"/>
<input type="text" name="Productqty2"/>
<input type="text" name="Productqty3"/>
<input type="button" name="RecalculatePrice" value="Recalculate Price"/ onClick="callDefault();">
<input type="text" name="ZipCode"/>
<input type="button" name="RecalculateShipping" value="Recalculate Shipping"/ onClick="callRecalculateShipping();">
<input type="text" name="Offercode"/>
<input type="button" name="RecalculateDisc" value="Recalculate Discount"/ onClick="callRecalculateDisc();">
<input type="button" name="CheckOut"/ onClick="callCheckout();">
</form>
<javascript>
function callCheckout(){
form.action="<some value>";
form.submit();
}
...so on with other functions...
</javascript>
Change input types to button .

How to get the values from a form and prevent submission?

I have this simple form:
HTML
<form>
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton"
onclick="doSomething();" type="submit">Create!</button>
</form>
JS
function doSomething() {
var name, email;
name = document.getElementById("eName").value;
email = document.getElementById("Email").value;
putElementsIntoTheDOM(name, email);
}
When the user inputs some information I want to populate the DOM with the user input.
The example above works. But I think it can be done better. I just don't know how.
How can I wire the <button> so that when the user clicks it the form values are passed
to the function doSomething()?
Also, since I'm not sending the form values anywhere except populating the DOM, how can I
prevent the submission?
I've seen something like this but I can't get it too work.
<button id="create" class="boton" onclick="doSomething(this.form);"
type="submit">Create!</button>
If you don't want to send the form values anywhere, then you just need to remove type="submit" from your button.
Your example code works fine. I'm not sure what you mean by a 'better' way. More modern/idiomatic javascript would not be using the onclick attribute, but instead binding doSomething to the button. Using jQuery, that would look like:
$("#create").click(doSomething);
First of all you have to update your function declaration to be able to receive the variables you want to send
function doSomething(name,email) {
}
Secondly, if you have to send values of some fields to that function, you can do so on button click like this.
<button id="create" class="boton" onclick="doSomething(document.getElementById('eName').value,document.getElementById('Email').value);" type="submit">Create!</button>
However, using unobtrusive javascript is recommended, and for that jQuery is one of the options you can use for passing variables to your function neatly.
There is a difference between the type="submit" and type="button" that I didn't realize.
Also, the button and submit types react differently with onclick and onsubmit events.
For example
<form onclick="doSomething()">
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton" type="button">Create!</button>
</form>
Notice that at the top of the form there is onclick.
The onclick is fired whenever you focus on an input element, and of course if you click the button.
Changing the form to <form onsubmit="doSomething(); but not changing the type="button" doesn't do anything. Clicking the button doesn't trigger the function.
By changing the type="submit"and keeping the head <form onsubmit="doSomething(); triggers the function when the button is clicked. A nice added functionality to this is that if you have any <input ... required="required"> the submit will only work if those fields are filled in (and your form will let you know about the required fields).
To prevent the submission/refreshing (since I'm only populating the DOM with user input) adding return false at the form head prevents submission
<form onsubmit="doSomething(); return false">.
Finally, to get the form values adding this:
<form onsubmit="doSomething(this); return false> and then
function doSommething(formInfo) {
var name = formInfo.eName.value;
var email = formInfo.Email.value;
...
}

how to submit the values in the form in javascript when there are 2 submit values?

I have one form where there are 2 inputs those are submit type of inputs like this.
<form>
<input type="text" name="payee" value="">
<input type="text" name="amount" value="">
<input type="text" name="date" value="">
<input type="submit" name="deposit" value="Distribute">
<input type="submit" name="distribute" value="Deposit">
</form>
In jQuery like this:
$("form submit").click(function() {
// i wrote code.
}
If I click on the deposit button some action should occur. If I click on the distribute button some other action should occur.
First of all you need to change your submit inputs to buttons (or at least one of them) as 2 submit buttons in 1 form is invalid. Then give each button its' own Id.
<input type="button" name="deposit" value="Distribute" id="distribute">
<input type="button" name="distribute" value="Deposit" id="deposit">
Then, in jQuery you can then use the Id of each button to run specific code when it is clicked, like this:
$("#distribute").click(function() {
// code to run when distribute is clicked
}
$("#deposit").click(function() {
// code to run when deposit is clicked
}
insert another input type :
<input type="hidden" name="hf" id="hf" value="">
and
$("form :submit").click(function() {
if ($(this).attr('id')=='distribute') $("#hf").val('sent by distribute');
else $("#hf").val('sent by deposit');
}
and in the server you can see who send by reading the hiddenField value ( hf)
You can add a custom attribute on your buttons in document.ready function and on click of the button you can identify which button has posted an request to form.
Example to add custom attribute
<input type="submit" id="deposit" value="Distribute">
<input type="submit" id="distribute" value="Deposit">
$(function () {
$("#deposit").attr('isDeposit','1');
$("#distribute").attr('isDeposit','0');
});
and on submit click
$("form submit").click(function()
{
var identifyButton = $(this).attr('isDeposit');
}
some thing like this.
Try to use the jQuery submit() function, like this:
$('#deposit').submit(function(){
//Code to run
});
It's better because you can cancel the client event, if some field is wrong.
http://api.jquery.com/submit/
You don't need a plugin to do it, however there's a lot of them:
http://www.designyourway.net/blog/resources/55-jquery-form-plugins-to-download-and-use/

Categories