I'm having problem to validate the form below.
The main issue is that I have to use the "onfocusout" function to validate the inputs.
The name input has be required depending of the radio selection.
When the "value3" is selected, the focus is set to the input.
While on the input, if the user tries to change the radio button, the onfocusout is triggered before the radio value is changed, and in that case the error is shown while it should not
Any suggestion?
<form id="myform">
<input type="radio" name="radio" value="value1" /> value1
<input type="radio" name="radio" value="value2" /> value2
<input type="radio" name="radio" value="value3" /> value3
<input type="text" name="name" />
<input type="submit" />
</form>
The js code is:
$("#myform").validate({
rules: {
name: {
required: {
depends: function () {
return $("input[name='radio']:checked").val() == "value3";
}
}
}
},
messages: {
name: {
required: "You must enter name"
}
},
onfocusout: function (element) {
this.element(element);
},
submitHandler: function (form) {
alert('success');
return false;
}
});
$("input[name='radio']").change(function () {
var value = $(this).val();
if (value == "value3") $("input[name='name']").focus();
else $("input[name='name']").valid();
});
JSFiddle: http://jsfiddle.net/954ros6L/
You are calling the .valid() method too late. Simply call it every time you change the radio buttons and the timing will be correct.
$("input[name='radio']").on('change', function () {
$("input[name='name']").valid(); // <- move it to here
var value = $(this).val();
if (value == "value3") {
$("input[name='name']").focus();
}
});
Plus, if you notice, the validation message now correctly appears when the field is invalid.
You also do not need a custom onfocusout handler.
DEMO: http://jsfiddle.net/954ros6L/4/
Sidenote:
You cannot use event.preventDefault() inside just any callback function since event is not a valid argument for the function. Besides, .preventDefault() is only meant to block the default action of an event, like stopping the page jump after an anchor click, etc. ... not the default behavior of a plugin.
To change the default behavior of onfocusout simply means that you write a function to override the plugin's default behavior, which you've already done.
Try using the following to prevent to normal event handlers
event.preventDefault();
Related
The text field looks like this:
<input type="text" id="nm" name="marks" value="60" onblur="return(myFunction())"/>
the button looks like this:
<input type="submit" value="submit" onclick="val();" />
The following is my function in onblur code:
function myFunction() {
var x = document.getElementById("nm");
if(x.value>12) {
alert("error");
x.value="0";
x.focus();
return false;
}
return true;
}
E.g., if the user changes value of the nm text field and clicks on the next text field then the alert must be shown (if returned false), but in case the user changes value of the the nm field and then clicks on the SUBMIT button, then the function code in the onclick in submit button must not run if onblur returned false. At present, the function in onclick gets executed if onblur returned false.
Please help me with a solution.
Option A:
save onBlur function return into a variable and acces it on the beginning of val() function to know if you have to execute the rest of the code or not.
Option B:
Modify button element interactively on onBlur.
Button with id="button"
<input type="submit" id="button" value="submit" onclick="val();" />
new onBlur function:
function myFunction()
{
var x = document.getElementById("nm");
var button = document.getElementById("button");
if(x.value>12)
{
button.removeAttribute("onclick");
alert("error");
x.value="0";
x.focus();
return false;
}
button.setAttribute("onclick", "val();");
return true;
}
Have in mind both options will require a valid onBlur() after and invalid one for onClick to work again.
I think onclcik function is enough to know value is greater than 12 or not
function val() {
var x = document.getElementById("nm");
if(x.value>12) {
alert("error");
x.value="0";
x.focus();
return false;
}
//do whatever you want
return true;
}
<input type="text" id="nm" name="marks" value="60" />
<input type="submit" value="submit" onclick="val();" />
I want to use an onlick event handler to validate some form fields using jquery Validate. To do this I have the following code:
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
<script>
$(".js-add-names").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Name: {
required: true
}
},
messages: {
Name: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Age: {
required: true
}
},
messages: {
Age: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
</script>
What I've noticed is that only one event handler works out the two based on whichever one was clicked first i.e. if I click the button with class js-add-names, the validation for that handler works as expected.
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work and vis versa?
Any ideas why this is happening and what is the fix?
* UPDATE *
Further to suggestion by Sparky I have re-written the code as below but now when I click js-add-names, the validation for that handler works as expected
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work becuase the validation has previously added a rule for input #Name. How do I reset the form or remove the rules each time the event handlers fire?
<form>
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
// other inputs
<input type="checkbox" name="CarOwner" value="Yes"> Car owner
<input type="submit" value="Submit">
</form>
<script>
$("form").validate();
$(".js-add-names").click(function (e) {
e.preventDefault();
$("#Age").rules("remove");
$("#Name").rules("add", {
required: true,
messages: {
required: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Name").val('');
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("#Name").rules("remove");
$("#Age").rules("add", {
required: true,
messages: {
required: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Age").val('');
});
</script>
Any ideas why this is happening and what is the fix?
The .validate() method is only used for initializing the plugin on your form and therefore should only be called once when the page is loaded. Subsequent calls are always ignored. So when you use one click handler, you initialize the validate plugin, and the other call to .validate() in the other click handler will do nothing.
The fix...
Call .validate() ONE time to initialize the plugin on your form.
Do NOT call .validate() from a click handler since this is not the testing method; it's only the initialization method.
Use the plugin's built-in submitHandler and invalidHandler functions for stuff you need to do when the form is valid and invalid.
Since you appear to be using your click handlers to add fields/rules to an existing form, then use the .rules('add') and .rules('remove') methods to add and remove any rules dynamically.
I have a situation where i want to validate the text entered into a input text field. This is the HTML code:
<div id="err_title" style="display:none;">Please enter a valid Number.</div>
<input type="radio" id="txt_a-radio" value="valueA" checked="checked">
<input type="text" id="txt_a">
<input type="radio" id="txt_b-radio" value="valueB">
<input type="text" id="txt_b" disabled>
By default #txt_b field will be disabled, when user clicks on #txt_b-radio button #txt_b will be enabled and #txt_a will be disabled.
The condition for validation is:
#txt_a can contain only 12 digit number
#txt_b can contain only 20 digit number
Validation should happen once user enters value in enabled field then clicks anywhere outside. If value entered by user is not valid error message #err_title should display.
Suppose if user enters value for #txt_a and then clicks on #txt_b-radio button then validation shouldn't happen since user has switched the input field.In this case #txt_a should be disabled and txt_b enabled.
I have tried with the following code:
$('#txt_a').change(function() {
custNumber = $('#txt_a').val(); expression = /^[0-9]{12}$/;
if(custNumber === '') {
$("#err_title").css('display', 'none');
} else if ((!custNumber.match(regexp))) {
$("#err_title").css('display', 'block');
} else {
$("#err_title").css('display', 'none');
}
});
$input1 = $('input[name="input1"]');
$input2 = $('input[name="input2"]');
$checkbox = $('input[name="checkbox"]');
$input1.on('change', function(e) {
var isValid = this.value.length >= 12;
this.classList.toggle('notValid', !isValid);
})
$checkbox.on('change', function(e) {
$input2.prop('disabled', !this.checked);
})
input.notValid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" />
<input type="text" name="input2" disabled />
<input type="checkbox" name="checkbox" />
NOTE:
In example above, I'm mixing vanillia JS, with jQuery. I would recommend avoiding it - I did that to show You how easy (well not always...) it is to do such a simple thing without jQuery.
Basically, if You want to do simple stuff like that, I would recommend to give up on jQuery.
ANSWER:
You are looking for jQuery change event. It triggers once input loose focus.
$(your_input).on('change', function(e) {...} )
You can validate input length like (function inside listener) :
var isValid = this.value.length === 12
Same goes with disabled/enabled input.
You have to attach event listener to checkbox
$(your_checkbox).on('change', function(e) {...} )
then You can get state of checkbox :
var isChecked = this.checked
and disable/enable Your input
$(your_input).attr('disabled', !isChecked)
Can I somehow insert the required attribute into an input field only if a certain radio is checked?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
My input looks like this:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
<input type="text" name="ladder-meters" id="ladder-meters" required>
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked
This may need some adjustment to suit your specific project.
This will work with this checkbox:
<input type='checkbox' id='ladder' name='ladder' />
Tried F. Orvalho, didn't work for me, I had to use
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
Easy to achieve with jQuery:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});
This question already has answers here:
Resetting a multi-stage form with jQuery
(31 answers)
Closed 9 years ago.
I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.
I do not have any HTML code to show, I need something generic.
Can you help?
Thanks!
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset() method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden".
UPDATE
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():
$('#myForm').trigger("reset");
UPDATE
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
To reset form (but not clear the form) just trigger reset event:
$('#form').trigger("reset");
To clear a form see other answers.
Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".
One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.
Note that this will not clear placeholder text.
Set the val to ""
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
You could also try something like this:
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
More info here and here
<form id="form" method="post" action="action.php">
<input type="text" class="removeLater" name="name" /> Username<br/>
<input type="text" class="removeLater" name="pass" /> Password<br/>
<input type="text" class="removeLater" name="pass2" /> Password again<br/>
</form>
<script>
$(function(){
$("form").submit(function(e){
//do anything you want
//& remove values
$(".removeLater").val('');
}
});
</script>
You can simply use the reset button type.
<input type="text" />
<input type="reset" />
jsfiddle
Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.
Reference: http://api.jquery.com/reset-selector/
I use following solution:
1) Setup Jquery Validation Plugin
2) Then:
$('your form's selector').resetForm();
function reset_form() {
$('#ID_OF_FORM').each (function(){
this.reset();
});
}
the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.
$.fn.resetForm = function() {
return this.each(function(){
this.reset();
});
}
Then just call it something like this
$('#divwithformin form').resetForm();
or
$('form').resetForm();
and of course you can still use it in the chain
$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')
Would something like work?
JQuery Clear Form on close
HTML
<form id="contactform"></form>
JavaScript
var $contactform = $('#contactform')
$($contactform).find("input[type=text] , textarea ").each(function(){
$(this).val('');
});
Simple and short function to clear all fields