I want to know how to reset a particular form field using jQuery.
I'm using the folowing function:
function resetForm(id) {
$('#'+id).each(function(){
this.reset();
});
}
but it is resetting all the fields. Is there any way to reset specific fields using jQuery or JavaScript? I want to reset only a particular field.
function resetForm(id) {
$('#' + id).val(function() {
return this.defaultValue;
});
}
example without using id:
http://jsfiddle.net/vYWdm/
The reset() method affects the whole form, by design, to reset only particular input elements, assuming that there's a Reset previous inputelement after eachinput`:
$('button.reset').click(
function(){
var input = $(this).prev('input:first');
input.val(''); // assuming you want it reset to an empty state;
});
JS Fiddle demo
To reset the input to its original state, then first I'd recommend storing the original value in a data-* attribute for recollection:
$('input').each(
function(){
$(this).attr('data-originalValue',$(this).val());
});
$('button.reset').click(
function(){
var input = $(this).prev('input:first');
input.val(input.attr('data-originalValue'));
});
JS Fiddle demo
Given HTML similar to the following (in which the input elements are grouped together):
<form action="#" method="post">
<fieldset>
<input value="something" />
<button class="reset">Reset the input</button>
</fieldset>
<fieldset>
<input type="checkbox" name="two" />
<input type="checkbox" name="two" checked />
<input type="checkbox" name="two" />
<button class="reset">Reset the input</button>
</fieldset>
<fieldset>
<input type="radio" name="three" checked />
<input type="radio" name="three" />
<button class="reset">Reset the input</button>
</fieldset>
</form>
The following jQuery will reset the input elements back to their page-load state:
$('button.reset').click(
function () {
$(this).prevAll('input').val(function(){
switch (this.type){
case 'text':
return this.defaultValue;
case 'checkbox':
case 'radio':
this.checked = this.defaultChecked;
}
});
});
JS Fiddle demo.
References:
attr().
prev().
reset()
val().
My approach would be to consider three cases: free-input-based fields, check-based fields and select-based fields.
$(set_of_fields).each(function() {
// Don't bother checking the field type, just check if property exists
// and set it
if (typeof(this.defaultChecked) !== "undefined")
this.checked = this.defaultChecked;
if (typeof(this.defaultValue) !== "undefined")
this.value = this.defaultValue;
// Try to find an option with selected attribute (not property!)
var defaultOption = $(this).find('option[selected]');
// and fallback to the first option
if (defaultOption.length === 0)
defaultOption = $(this).find('option:first');
// if no option was found, then it was not a select
if (defaultOption.length > 0)
this.value = defaultOption.attr('value');
});
Edit: I just noticed this won't work with <select multiple> fields.
You could do (if you plan to use the reset() javascript method):
function resetForm(id) {
document.getElementById(id).reset();
}
There is no need for jQuery as the method "reset" is a standard javascript method
Related
I have a form that has multiple elements/types
inputs for name, email, address, etc.
radio button for shipping speed.
select tags for "state" & "credit card type".
I want to disable the submit button until the:
1.inputs are filled out.
the select tags have an option selected
the radio is checked.
I've selected the elements (see below);
const btn = document.querySelector('#olegnax-osc-place-order-button');
let inputs = document.querySelectorAll('#olegnax-osc-billing-address-list .required-entry, input#authorizenet_cc_number');
let selectTags = document.querySelectorAll('#olegnax-osc-billing-address-list select, #payment_form_authorizenet select');
let radio = document.querySelector('#s_method_owebiashipping1_id_06');
My question is, being the form consists of 3 different types (input, select, radio), can I just create one array with all of these elements and loop though to make sure the value for each is not blank?
For example, say I store all the different elements in an array called "requiredFields" would this work?:
for (var i = 0; i < requiredFeilds.length; i++) {
if (requiredFeilds[i].value === '') {
btn.disabled = true;
}else {
btn.disabled = false;
}
}
There's a lot more to form validation than meets the eye, but that being said you have a major flaw in your logic. Namely, as you loop over all the fields, you could be changing btn.disabled back and forth depending on the value of the form field (or lack of a value).
Instead, begin with the button disabled, and then instead of looping, use Array.prototype.some (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to check if any field is missing a value, something such as:
btn.disabled = requiredFields.some(field => field === '');
There's lots else to address with regards to your approach but this corrects your current logic error and is much more concise.
You can loop through everything but the radio buttons easily. For the radio buttons, you want to check if any of the buttons in a radio group are checked, so it is a little more complicated. It might be easier to just designate a radio button as default, with the checked attribute:
document.querySelector("input[type=submit]").disabled = true;
const inputs = Array.prototype.slice.call(document.forms["form1"].querySelectorAll("input[type=text], select"));
document.forms["form1"].addEventListener("input", () => {
let complete = true;
inputs.forEach((field) => {
if(field.value.trim() === "") {
complete = false;
}
});
document.querySelector("input[type=submit]").disabled = !complete;
});
form{
display:flex;
flex-flow:column;
align-items:flex-start;
}
<form name="form1" id="form1">
<input type="text" name="bar" />
<input type="text" name="foo" />
<select name="biz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<select name="baz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<label>
A <input type="radio" name="buzz" value="a" checked />
</label>
<label>
B <input type="radio" name="buzz" value="b" />
</label>
<input type="submit" value="Submit" />
</form>
Yes, just combine your selectors and use a comma, and check tagName:
const requiredFields = document.querySelectorAll( "
#olegnax-osc-place-order-button,
#olegnax-osc-billing-address-list .required-entry,
input#authorizenet_cc_number,
#olegnax-osc-billing-address-list select,
#payment_form_authorizenet select,
#s_method_owebiashipping1_id_06
" );
for( let input of requiredFields ) {
if( input.tagName == "INPUT" ) {
}
else if( input.tagName == "SELECT" ) {
}
else if( input.tagName == "TEXTAREA" ) {
}
}
You should also use the required attribute too:
<input type="text" required />
<select required></select>
<textarea required></textarea>
I wrote some code using jQuery to convert <input> field values from one unit system to another (English <-> Metric). All was going well until I have realized that I am using a class selector, so instead of each value doing its conversion individually, all values (with same class) get converted to the same identical value (equal to the first occurrence of class).
An obvious solution is to assign an id to each value, which I suppose will work, but I am here to ask if there is a better way. I have a lot of values (which is why I tried using class), and would like to avoid using id, if possible. But, all I am looking for is "convert each value individually (using my conversion function)". How can this be done?
jQuery
function convertValues() {
if ($('#unit_system').val() == "English") //if changed to English
{
$('.value_gpm').val( //do converstion from Metric to English
convert($('.value_gpm').val(), "m3h", "gpm")
);
}
else if ($('#unit_system').val() == "Metric") //if changed to Metric
{
$('.value_gpm').val( //do conversion from English to Metric
convert($('.value_gpm').val(), "gpm", "m3h")
);
}
}
Calling Function
//below code is for select box (HTML for it is not shown)
$("#unit_system").change(function(){ //select box change detected
convertValues(); //function is called
});
HTML at first (before Select box change)
<input type="text" class="value_gpm" name="design_a" value="444" />
<input type="text" class="value_gpm" name="design_b" value="555" />
<input type="text" class="value_gpm" name="design_c" value="666" />
<input type="text" class="value_gpm" name="design_d" value="777" />
<input type="text" class="value_gpm" name="design_e" value="888" />
HTML after (after Select box is changed)
<input type="text" class="value_gpm" name="design_a" value="1954.87" />
<input type="text" class="value_gpm" name="design_b" value="1954.87" />
<input type="text" class="value_gpm" name="design_c" value="1954.87" />
<input type="text" class="value_gpm" name="design_d" value="1954.87" />
<input type="text" class="value_gpm" name="design_e" value="1954.87" />
Expected behavior: conversion produces different value per row
Actual behavior: same value produced for each row
Just loop through them, something like this.
var inputs = $('.value_gpm');
for(i=0;i < inputs.length; i++){
var input = inputs[i];
input.val( convert(input.val(), "m3h", "gpm") );
}
Best bet - using $.each and $(this).
$(document).ready(function(){
var valueEls = $('.value_gpm');
$("#unit_system").change(function(){
var unit = $(this).val();
switch(unit){
case "English":
valueEls.each(function(){
$(this).val(convert($(this).val(), "m3h", "gpm");
});
break;
case "Metric":
valueEls.each(function(){
$(this).val(convert($(this).val(), "gpm", "m3h");
});
break;
}
});
});
Use each()
$("value_gpm").each(function () {
convert(this.val(), ...etc
The less lines of codes I figure out for this is this:
var unit_system = $('#unit_system').val();
$('.value_gpm').each(function(){
convert($(this).val(), unit_system == "English" ? "m3h" : "gpm", unit_system == "English" ? "gpm" : "m3h");
});
You can use jQuery each:
$("#unit_system").change(function(){
var fromUnit = "m3h";
var toUnit = "gpm";
if ($(this).val() == "Metric"){
fromUnit = "gpm";
toUnit = "m3h";
}
$('.value_gpm').each(function(){
$(this).val(convert($(this).val(), fromUnit, toUnit));
});
});
New to JQuery:
Okay I am confused and have tried all variations, including what I have read in books and the JQuery API.
I have the following sample Mark-up:
<form id="myForm" name="myForm" action="" method="post">
<label>*Enter Input A:
<br />
<input type="text" id="inputA" name="inputA" />
</label>
<label>*Enter Input B:
<br />
<input type="text" id="inputB" name="inputB" />
</label>
<label>*Enter Input C:
<br />
<input type="text" id="inputC" name="inputC" />
</label>
<label>*Enter Input D:
<br />
<input type="text" id="inputD" name="inputD" />
</label>
</form>
<p class="myText">Sample Text</p>
When the page loads and I tab through the fields/textboxes, the paragraph color changes.
Which is what I want: blur function.
What I don't understand:
The paragraph does not change unless I type a value into the last textbox inputD.
Why? I need the paragraph to change if there is a value in any of the boxes.
Does this hold only one value? ($(element).val() == '')?
Here is the JQ:
$('#myForm :input[type="text"]').blur(function () {
$('#myForm input[type="text"]').each(function (i, element) {
if ($(element).val() == '') {
$(".myText").css("color", "#F00")
} else {
$(".myText").css("color", "#9A9A9A")
}
});
});
A fiddle is here: JSfiddle Example
Thanks for the explanation
You are not breaking out of the loop once you meet the desired condition. Instead you are looping through all textboxes and eventually if last one does not have any value it will be set to red color no matter whichever prev ones has values as that is the last one in the iteration. Instead you can break out of .each() loop using return false;
$('#myForm :input[type="text"]').blur(function () {
$('#myForm input[type="text"]').each(function () {
if (this.value == '') {
$(".myText").css("color", "#F00")
} else {
$(".myText").css("color", "#9A9A9A");
return false;
}
});
});
For that matter you could reduce it down to:
$('#myForm :input[type="text"]').blur(function () {
$('.myText').css('color', function () { //use the css function callback
return $('#myForm input[type="text"]').filter(function () { //Use filter to return the textboxes which has value
return this.value != ''
}).length == 0 ? "#F00" : "#9A9A9A"; // set the color accordingly
});
});
Fiddle
I updated your code, please check fiddle
http://jsfiddle.net/Wmrh6/11/
you should change paragraph color when u break out of the loop:
if(changed)$(".myText").css("color", "#9A9A9A");else
$(".myText").css("color", "#F00");
I have a form that submits values to database via Ajax and works fine but I also need to give option to user to reset the form to its default values in case they make a mistake.
The default values are stored in a javascript variable as json object
{"field_name1":"2","field_name3":"3","field_name3":"1000"...
problem I have is that the form has multiple input types , textarea , select , radio
and I need to figure out what they are based on the object key , look for name and return type , so I could do something like if radio set checked checked and so on
I tried
Object.each(dafaultValues, function(value, key){
var filed_name = MyForm.elements[''+key+''];
console.log(filed_name.type);
});
problem with this is that radio type have same name but different id's
<input type="radio" name="field_name5" id="field_name51" value="1">
<input type="radio" name="field_name5" id="field_name52" value="1" checked="checked">
and I endup with js error
Uncaught TypeError: Cannot read property 'type' of undefined
so what would be the best way to find out what the input type is before I can do
if(field.type ='radio'){
//set checked checked..
}
Take a look at this example. I just put it together very dirty, but you will get the idea ;)
HTML:
<form id="test">
<input type="radio" name="abc" value="1"/>
<input type="radio" name="abc" value="2"/>
<input type="radio" name="abc" value="3"/>
<input type="text" name="def" value="change" />
</form>
JS:
var values = {
'abc': '2',
'def': 'original'
};
var els = $('test').getElements('[name="abc"], input');
els.each(function(el) {
var defaultVal = values[el.get('name')],
type = el.get('type');
if (typeof defaultVal != 'undefined') {
return;
}
if (type == "radio") {
if (el.get('value') == defaultVal) {
el.set('checked', 'checked');
} else {
el.erase('checked');
}
}
if (type == "text") {
el.set('value', defaultVal);
}
});
<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>
and js:
var type = this.type.value;
alert(type);
How to fix it ?
In what context does that JS code run? If this is the radio button in question then this.value will return the value.
If your question is "How do I get the value of the currently selected radio button in the 'type' group?" then you may need to do something like this:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
for (i=0; i < rads.length; i++)
if (rads[i].checked)
return rads[i].value;
return null; // or undefined, or your preferred default for none checked
}
var checkedValue = getCheckedRadioValue("type");
(It would be easier with .querySelector() or .querySelectorAll(), but not all browsers support them.)
Just use selectors.
With jquery
$("input[name=type]:checked").val();
Or without jquery:
document.querySelector("input[name=type]:checked").value;
Just use this.value instead of this.type.value.
this.value will select the value associated with the value attribute of the input. (That's a mouthful).
Using jQuery you can do like this
$(function() {
$(".rad").click(
function() {
alert(this.value);
});
});
See this JSFiddle