I have two sets of checkboxes, named pizzaBase and pizzaTopping. I want to validate my form so that on submission at-least 1 base and topping must be selected.
function main() {
var form = document.getElementById('formname');
form.addEventListener('submit', validate);
}
function validate(event) {
var form = document.getElementById('formname');
if(!form.pizzaBase.checked) {
alert("select a base");
event.preventDefault();
}
else if(!form.pizzaTopping.checked) {
alert("select topping");
event.preventDefault();
}
else {
return true;
}
}
Problems
Only first if statement works.
Form submits true if checkbox is checked and then unchecked before
submission.
Doesn't validate, doesn't work.
Where am I going wrong?
Thank you GG for pointing out JS is working, I have HTML below if someone wouldn't mind correcting me. I basically have two identical versions of the below code, one for bases and the other toppings.
**
HTML
**
<section>
<h2> Bases </h2>
<p><input type="checkbox" name="pizzaBase" data-price="1.00" data-human-desc = "Small" value="Small"> Small (£1.00) </p>
<p><input type="checkbox" name="pizzaBase"data-price="1.50" data-human-desc = "Medium" value="Medium"> Medium (£1.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="2.50" data-human-desc = "Large"value="Large"> Large (£2.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="3.50" data-human-desc = "XLarge"value="XLarge"> XLarge (£3.50) </p>
</section>
Not sure if I should ask a separate question here, but this is my messy HTML. Is it the sections? I was trying to split each set of check boxes (bases, toppings) into two separate sections so used this tag.
Any ideas?
When you have multiple inputs with the same name, form.elementName will be an array-like list of elements.
The list won't have a checked property. Each item within it will.
You need to loop over the list and check to see if any of the elements are checked.
function areAnyChecked(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].checked) {
return true;
}
}
return false;
}
if(! areAnyChecked(form.pizzaBase)) {
...
Related
I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
var value = $('input:radio[name="radiogroupname"]:checked').val();
I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})
I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
var value = $('input:radio[name="radiogroupname"]:checked').val();
I have a poll with a couple a questions. Here is html code
<form id="pool">
<div class="questions>
<input type="radio" name="sex">Male
<input type="radio" name="sex">Female
</div>
<div class="questions>
<input type="radio" name="hair">Brown
<input type="radio" name="hair">Blonde
</div>
.... a lot of qestions div's
</form>
What to do so after the form is submitted to be sure that there is a checked radio button in all div`s ?
If you know how many groups you have you can just do:
if($('#pool input:radio:checked').length < numGroups){
// At least one group isn't checked
}
Otherwise you need to count the number of groups first. I can't think of any way to do this better then:
var rgroups = [];
$('#pool input:radio').each(function(index, el){
var i;
for(i = 0; i < rgroups.length; i++)
if(rgroups[i] == $(el).attr('name'))
return true;
rgroups.push($(el).attr('name'));
}
);
rgroups = rgroups.length;
if($('#pool input:radio:checked').length < rgroups)
alert('You must fill in all the fields.');
else
alert('Thanks!');
set default values or create handler for submit button and check if some values was checked. If no radio button is checked, show error message and do not submit form ( return false)
Untested code, but this is the idea:
if($('#pool').children().length == $('pool
div').find('#pool input:radio:selected').length) {
//do stuff
}
You can use the jquery validate plugin
from my experience this plugin is very efficient
I am trying to make a page that allows users to select 8 checkboxes from a total of 25.
Im wondering, how to detect the exact order in which they check them. I am using a plain html front page that will be verified by a form action pointing to a php page.
Im trying to get a result like (checkbox1,checkbox2,checkbox6,checkbox3,checkbox7,etc) for eight checkboxes, and the exact order in which they were clicked.
I think I have found what I am looking for,Im not too sure, but Im having trouble implementing it.
This is what I have so far, I guess my question is, what type of php do I need to gather this info once a user has submitted the form.
For the form I have:
<form id="form1" name="form1" method="post" action="check_combination.php">
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" onclick="setChecks(this)"/> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" onclick="setChecks(this)"/> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" onclick="setChecks(this)"/> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" onclick="setChecks(this)"/> Option 4
</form>
For the Javascript I have:
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=8
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
<script type="text/javascript">
<!--
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
//-->
</script>
I have gotten the part that only allows 8 checkboxes to be checked, but Im stuck as to what I need to do to actually parse the data once it has been submitted to a page with a name like check_combination.php.
I would appreciate any help
create a hidden input field with the order
update this input field when something changes
you'll have the order ready to be processed by PHP