Find class inside form validation function - javascript

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

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>

Validate input type=number min=... single field, no form [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>

HTML5 required attribute trigger action with jQuery

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

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

Jquery submit form error

I have a form which I want to submit upon button click which is outside the form, here is my HTML :
<form id="checkin" name="checkin" id="checkin" action="#" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
</form>
Here is my jQuery :
$("button").live('click', function() {
$("#checkin").submit();
});
$("#checkin").live('submit', function() {
});
When I click submit button inside the form its submitting ok, but its not submitting when I click on the button which is outside the form tags, why? how can I fix this ?
You are selecting all the <button> elements but you are trying to select an <input>.
It works when it is inside the form because the the normal submit functionality runs.
Change the selector to match the element you actually have: input[type=submit]
Better yet, forget about the JS and just structure your HTML better so that the submit button is inside the form.
If you're handling the form processing using JavaScript, then you'll want to return false in your button and form processing code.
I was able to achieve identical results using the JavaScript below, and the two HTML examples (with the button inside and outside of the form element).
JavaScript/jQuery
$("button").live('click', function() {
$("#checkin").submit();
return false;
});
$("#checkin").live('submit', function(){
alert("Hello world!");
return false;
});
HTML Example 1
Button inside the form.
<form id="checkin" name="checkin" id="checkin" action="" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
<button>test</button>
</form>
HTML Example 2
Button outside the form.
<form id="checkin" name="checkin" id="checkin" action="" method="post">
<input type="text" tabindex="100" class="identifier" name="identifier" id="identifier">
<input type="submit" tabindex="101" value="Submito" class="elsubmito" name="submit">
</form>
<button>test</button>
As I said, both examples performed as expected. You may want to double-check your button listening code to ensure that you are in fact using the button element. If you're using an element with the id attribute set to button, then you'll want to ensure you are using the proper jQuery selector:
$("#button").live('click', function() { // ...
you can have a simple hyperlink outside of your form like this
click to submit and that's all you need

Categories