Javascript and only one Checkbox - undefined - javascript

for (i = 0; i < document.checks.user.length; i++) //for all check boxes
{
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
<body>
<form action="" method=POST name="checks" ID="Form2">
I have a bike:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<br>
<br>
</form>
<input type="button" value="Delete"
class="btn" onclick="sub_delete()"
onmouseover="hov(this, 'btn btnhov')" onmouseout="hov(this, 'btn')"
id="Button1" name="Button1"
/>
</body>
as you probably already know when there is only one check box left document.checks.user.length = undefined. Whats the most efficient way to make sure that when there is only one check box, it will be deleted. I was thinking just thinking to add it as a seperate if statement before the if statement here.....any suggesstions.
Thanks.

Use a loop control variable, and set it to 1 if length is undefined...
var len = document.checks.user.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++) //for all check boxes
Best regards...

if (document.getElementById('Checkbox1').checked) { /* do something */ }
if you want to loop a bunch of checkboxes, you could loop the input fields of your form, like:
var formNodes = document.checks.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
}

if(document.checks.user[0]) {
//it's an array
}
else {
//it's a single element
}

Your question is somewhat confusing, since your javascript would obviously have to be inside a function called 'sub_delete' to be any use... someone with the mighty power to edit questions might improve the question by making that clearer...
So the first issue you have to get around is the fact that for single checkbox, with a given name 'user', is not an array, and therefore has no defined length, but also if you try and access it as an array.. things get confused.. a full rewrite of your javascript function might look like this:
function sub_delete{
if (typeof document.checks.user.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.checks.user.checked == true )
{
document.checks.submit();
return 0;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.checks.user.length; i < max; i++){
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
}
}//sub_delete end
HTH,
-FT

I too face the same proble with total of 5 checkboxes out of which 4 are disabled and 1 is enabled. Now the checkboxId.length is undefined, so the only option I could think of is if(checkboxId.length ==undefined ){checkboxId.checked=true & submith the form}.

It's very simple, just create a hidden input tag with the name same as the existing checkbox input tag.
For example:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<input type="hidden" name="user" value=""/>

I'd probably iterate across document.checks.elements, looking for .type == 'checkbox'.

jQuery is your friend:
$("input[type='checkbox']").attr('checked', false);
(... if jQuery is available to you?)

Related

The radio inputs from my html are not interacting well with my if statements in javascript [duplicate]

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

JavaScript - Toggle "check all" checkboxes true/false

I am trying to make "toggle checkboxes" function, as below:
HTML Code:
<!-- "Check all" box -->
<input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" />
<!-- the other ones -->
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
JavaScript:
function selectbox( eID ) {
// instead of writing the element id in the html code,
// i want to use "this.getAttribute( 'id' )"
var c = document.getElementById( eID );
// now when we've got the id of the element,
// let's get the required attribute.
var box = c.getAttribute( 'name' );
// set var i value to 0, in order to run "for i" loop
var i = 0;
for(i; i < box.length; i++) {
// now lets find if the main box (as box[0]) checked.
// if returns true (it has been checked), then check all - else -
// do not check 'em all.
if(box[0].checked == true) {
box[i].checked = true;
}
else {
box[i].checked = false;
}
}
}
I don't want any jQuery solution (even if it can be easier than pure js), so please avoid suggesting it. All I want to know is - If I'm wrong - what do you think I should do to solve this?
Thank you very much. every suggestion/tip is appreciated.
Your problem mainly seems to be that you are iterating over the checkbox name, not the checkboxes with that name.
var box = c.getAttribute( 'name' );
Now, box is equal to "check", so box[0] is "c", box[1] is "h" etc.
You need to add this:
var boxes = document.getElementsByName(box);
And then iterate over boxes.
Of course, at that point, you may want to rename your variables too.
Given the name in the variable box, you can check all boxes with the same name like this:
Array.prototype.forEach.call(document.getElementsByName(box), function(el) {
el.checked = true;
});
(Array.prototype.forEach.call is used to loop over the "fake-array" returned by getElementsByName because the NodeList class doesn't have forEach.)
I think you can further simply your code by not passing the element's ID to your function, but directly the name (selectbox(this.name)). Also note that you can access ID and name using .id and .name instead of using getAttribute.
You can make it simple.
HTML Code:
input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox(this.getAttribute('name'));" />
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
Javascript:
function selectbox(eID) {
var checkBoxes = document.getElementsByName(eID);
for (var i = 0; i < checkBoxes .length; i++) {
if (checkBoxes[0].checked) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
}

select checkboxes with javascript based on html-5 data attribute

This code is not working:
function autoScrub() {
checkLength = document.querySelectorAll("input[type=checkbox]");
for (var i=0; i < checkLength.length; i++) {
if (checkLength[i].attr('data-z') === 1) {
checkLength[i].checked = true;
}
}
}
Each of my checkboxes has a data-z attribute of either 1 or 0. I'd like to auto-check all of the checkboxes that have a data-z attribute of 1. The code is breaking at if (checkLength[i].attr('data-z') === 1) { as apparently I cannot read the data-attribute this way.
Apart from this the rest of the code works fine. I can use checkLength[i].checked = true; and it will check all of the checkboxes, I just can't reference its data-attribute correctly in an if statement and I'm not sure how to.
Any ideas?
Update
I screwed around with two of the solutions below and finally came up with:
function autoScrub() {
$("input:checkbox").each(function() {
if ($(this).data("z") == 0) {
$(this).prop('checked', true).trigger('change');
}
});
}
and this worked. Thank you everyone for your help!
in jQuery this is one line of code:
$('input[type="checkbox"][data-z="1"]').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
EDIT
Just noticed a comment about firing the change event:
$('input[type="checkbox"][data-z="1"]').prop('checked', true).trigger('change');
https://api.jquery.com/trigger/
DOM element nodes don't have an .attr() method. I think you're looking for .getAttribute().
if (checkLength[i].getAttribute('data-z') === "1") {
checkLength[i].checked = true;
}
Also note that your attribute values will be strings, not numbers, so you'll either need to compare to strings as in my edit above, or else compare with ==.
Since you tagged your post with the jQuery tag, I'll add that your code would look like this if you were to go that route:
$("input:checkbox").each(function() {
if ($(this).data("z") == 1)
this.checked = true;
});
if you want to use pure html5 then use HTMLElement.dataset
// el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
// 'someDataAttr' in el.dataset === false
// el.dataset.someDataAttr = 'mydata';
// 'someDataAttr' in el.dataset === true
(function autoScrub() {
var el = document.querySelectorAll("input[type=checkbox]");
for (var i=0; i < el.length; i++) {
console.log(el[i].dataset.z)
if (el[i].dataset.z === "1") {
console.log(el[i]);
el[i].checked = true;
}
}
})();
<input type=checkbox id=check-1 data-id=111111 data-user=john data-date-of-birth=2jan2010 data-z=1 />
<input type=checkbox id=check-2 data-id=222222 data-user=tambo data-date-of-birth=3feb2011 data-z=2 />
<input type=checkbox id=check-3 data-id=333333 data-user=sandra data-date-of-birth data-z=3 />
<input type=checkbox id=check-4 data-id=444444 data-user=loic data-date-of-birth=4mar2012 data-z=4 />
Note: Accessing the Data
The W3C HTML5 spec has a clear method for collecting data in
JavaScript. Notice that we don’t need the “data-” in front of our
value like with getAttribute; we just call our value name directly.
This access method meets the spec, but like many HTML5 features, it
only works in HTML5 browsers.

Enable submit when all form items are valid

I need some help with something... say I have the following form...
<form name="" id="" method="" action="">
<input type="text" id="text1" name="text1" />
<br />
<br />
<input type="text" id="text2" name="text2" />
<br />
<br />
<input type="text" id="text3" name="text3" />
<br />
<br />
<input type="text" id="text4" name="text4" />
<br />
<br />
<input type="submit" value="let's go" disabled="disabled" />
</form>
Now I want to have a simple script to enable the submit when the values of the text boxes are not an empty string or null...
So I have something like this.. which I will bind to the window.onload
function enableButton(){
var formitemsArray = ['text1','text2','text3','text4'],
i;
// Loop through all items
for(i=0;i<formitemsArray.length;i++){
// validate the length on the keypress...
formitemsArray.onkeypress = function(){
// loop through all the items again
for(j=0;j<formitemsArray.length;j++){
if(formitemsArray[j] == "" || formitemsArray[j] == null ){
// return false or something???
}else{
document.getElementById("submitButton").disabled = false;
}
}
}
}
}
Now I think I'm on the right lines to a solution but I'm getting lost when trying to make sure that all the items are greater than a zero length string as I'm returning false too soon. Can someone set me straight please?
Welcome to event bubbling!
This does the following: listen to an event (onkeypress) on the whole element and all its children! Which means you can do the following:
document.getElementById('form-id').onkeypress = function(e) {
var text1 = document.getElementById('text1'),
text2 = document.getElementById('text2'),
text3 = document.getElementById('text3'),
text4 = document.getElementById('text4')
if (text1.value.length > 0 &&
text2.value.length > 0 &&
text3.value.length > 0 &&
text4.value.length > 0) {
document.getElementById('submit-button').disabled = false
}
// As an aside, for later: if you want to get the element
// that triggered the event, you have to do the following
// to be cross-browser:
var evt = e || window.event, // IE doesn't get the event passed by argument
target = e.target || e.srcElement // 'target' is official, old versions of FF used 'srcElement'
// With the 'target' variable, you can now play.
}
There is another more generic solution, but it might not fit your needs (note that it requires a forEach shim:
// Declare a counter variable
var count = 0
document.getElementById('form-id').onkeypress = function(e) {
// Get all the inputs!
var inputs = this.getElementsByTagName('input')
// Now loop through all those inputs
// Since a NodeList doesn't have the forEach method, let's borrow it from an array!
[].forEach.call(inputs, loopThroughInputs)
}
function loopThroughInputs(input) {
// First check the type of the input
if (input.type === 'text') {
// If the value is correct, increase the counter
if (input.value.length > 0) {
count++
}
// If the 4 inputs have increased the counter, it's alright!
if (count === 4) {
document.getElementById('submit-button').disabled = false
}
}
}
And now this code was proposed by #Esailija, and it is way better and cleaner. However, it also requires ES5-Shim (for the every method):
document.getElementById('form-id').onkeypress = function(e) {
var inputs = [].slice.call( this.querySelectorAll( '[type=text]') );
document.getElementById('submit-button').disabled = !inputs.every(function(input){
return !!input.value;
});
}
(This guy is brillant, just don't tell him)
There are a few ways you can do this... One would be to keep the button enabled but use javascript to check the validity of the form data upon submission. The benefit to this is that the validation code is only run once, when the user clicks submit and is expecting his data to be validated (at least I do) .
function validateForm() {
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
if( formElement.elements[i].value.length === 0 ) {
return false;
}
return true;
}
}
The other way is live validation, which would validate each input onBlur (focus lost). This method has the benefit of showing the user in real time what values are bad, however this can be very resource heavy depending on the number of form elements and the way you introduce the check.
Personally I would go with my first suggestion; however with that said if you choose to validate each element, I would do so like this:
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
formElement.elements[i].addEventListener('blur', function() {
if( this.value.length === 0 ) {
alert('this input is invalid');
}
}, false);
}
The latter method also requires you hold onto a 'state' variable to determine whether or not the form is valid upon submission, or check all the values again.
Hope this sheds some light, and I hope my code examples help some.
If possible use jquery validation plugin instead of re-inventing the code, http://docs.jquery.com/Plugins/Validation its so easy to use.
In this jsfiddle you'll find a way to monitor the progress of form contents. If all the field conditions are fulfilled, a submit button is shown. Maybe it's useful for you. Bare in mind that client side checking of a form may be tampered with, so you always need a server side check too, if your data need to adhere to certain requirements. In other words: client side form checks are merely usability enhancements.

How to get the selected radio button’s value?

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

Categories