Checking Value of Radio Button Group via JQUERY? - javascript

This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
How do I retrieve the value of gender via JavaScript?

Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value

In pure Javascript:
var genders = document.getElementsByName("gender");
var selectedGender;
for(var i = 0; i < genders.length; i++) {
if(genders[i].checked)
selectedGender = genders[i].value;
}
update
In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList :
var form_elements = document.getElementById('my_form').elements;
var selectedGender = form_elements['gender'].value;
The only catch is that RadioNodeList is only returned by the HTMLFormElement.elements or HTMLFieldSetElement.elements property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.

If you are using a javascript library like jQuery, it's very easy:
alert($('input[name=gender]:checked').val());
This code will select the checked input with gender name, and gets it's value. Simple isn't it?
Live demo

To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.
<form name="myForm">
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
</form>
<script>
var selected = document.forms.myForm.gender.value;
</script>

Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}

Another solution for ES5+
[...document.getElementsByName("gender")].find(input => input.checked).value;

Without loop:
document.getElementsByName('gender').reduce(function(value, checkable) {
if(checkable.checked == true)
value = checkable.value;
return value;
}, '');
reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.
The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.

function myFunction() {
document.getElementById("text").value='male'
document.getElementById("myCheck_2").checked = false;
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction_2() {
document.getElementById("text").value='female'
document.getElementById("myCheck").checked = false;
var checkBox = document.getElementById("myCheck_2");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
Male: <input type="checkbox" id="myCheck" onclick="myFunction()">
Female: <input type="checkbox" id="myCheck_2" onclick="myFunction_2()">
<input type="text" id="text" placeholder="Name">

Related

Removing value from array according to index using splice()

I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>

Enable button if radio button selected

I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok

JavaScript Validation For Checkbox, When Multiple checkbox selected from option list

I want to do JavaScript validation for Checkbox
If Value from Checkbox is not selected, it should get alert "Please Select Languages You Know"
But if user select 2 Languages from list of checkbox. I need that 2 languages should get alert using JavaScript.
I know to do with single checkbox, but not getting how to do using array.
Here is my Code...
<script type="text/javascript">
function myFunction(form){
var i,
chks = document.getElementsByName('lang[]');
for (i = 0; i < chks.length; i++){
if (chks[i].checked){
//Here how i should alert selected values
return true;
}else{
alert('No item selected');
return false;
}
}
}
</script>
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<div id="languageId"><label>Language : </label>
<input type="checkbox" name="lang[]" value="english" >English</input>
<input type="checkbox" name="lang[]" value="marathi">Marathi</input>
<input type="checkbox" name="lang[]" value="hindi">Hindi</input>
</div>
<div id="submit1"><button type="submit">Submit</button></div><br/>
</form>
Thank You,
Rahul
If you want to get the list of selected checkbox values.. you can use this..
$('#someButton').click(function() {
var values= [];
$('#MyDiv input:checked').each(function() {
values.push(this.val);
});
// now values contains all of the values of checked checkboxes
// do something with it
});
If you only need one selected value, it's easier to use a radio input type. With it, you can find the selected value using a querySelector (see MDN). For multiple languages, you can also use querySelectorAll, convert its results to an Array and use Array.map (see MDN) to map the results into an Array of the values of the checked checkboxes.
Here's your snippet rewritten for both cases (without a form):
(function (d, w, undefined) {
d.querySelector('#languageId button').addEventListener('click', doSubmit);
d.querySelector('#multiLanguageId button').addEventListener('click', doSubmitMulti);
var languageSelectorContainer = d.querySelector('#languageId');
var multiLanguageSelectorContainer = d.querySelector('#multiLanguageId');
function doSubmit() {
var languageChecked = languageSelectorContainer
.querySelector('[type=radio]:checked');
d.querySelector('#result').innerHTML =
'your selected language: <b>'+
(languageChecked
? languageChecked.value
: 'not yet selected') +
'</b>';
}
function doSubmitMulti() {
var languagesChecked = [].slice.call(
multiLanguageSelectorContainer
.querySelectorAll('[type=checkbox]:checked') )
.map(function (v){
return v.value;
});
d.querySelector('#result').innerHTML =
'you selected these language(s): <b>'+
(languagesChecked.length
? languagesChecked.join(', ')
: 'none yet selected') +
'</b>';
}
}(document, window))
<div id="languageId">Pick your language:
<input type="radio" name="lang[]" value="english">English
<input type="radio" name="lang[]" value="marathi">Marathi
<input type="radio" name="lang[]" value="hindi">Hindi
<button>Submit</button>
</div>
<div id="multiLanguageId">Pick the languages you know:
<input type="checkbox" name="mlang[]" value="english">English
<input type="checkbox" name="mlang[]" value="marathi">Marathi
<input type="checkbox" name="mlang[]" value="hindi">Hindi
<button>Submit</button>
</div>
<div id="result"></div>

how to pass checkbox values in an array to a function using onclick in javascript

how to pass checkbox values in an array to a function using onclick in JavaScript.
following is my html code. Note that I don't use form tag. only input tags are used.
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query with the parameter as shown below
<button onclick="onclickhandler()">CLICK</button>
then
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick handler.
Note: Also ID of elements must be unique in a document... you have multiple elements with id a, I'm not seeing you using that id anywhere so you could probably remove it
With pure javascript (demo) (tested with Chrome only).
HTML :
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript :
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
Try this
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}

In JavaScript, how can I get all radio buttons in the page with a given name?

Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:
Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?
I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.
You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:
function getCheckedValue( groupName ) {
var radios = document.getElementsByName( groupName );
for( i = 0; i < radios.length; i++ ) {
if( radios[i].checked ) {
return radios[i].value;
}
}
return null;
}
getElementsByName didn't work for me. I did this:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
nbchecked++;
}
}
Use document.getElementsByName() is the short answer to the question you asked.
However, it may be better to do something like this:
<form name="formFoo">
Foo: <input type="radio" name="groupFoo" value="foo" checked> <br />
Bar: <input type="radio" name="groupFoo" value="bar"> <br />
Baz: <input type="radio" name="groupFoo" value="baz"> <br />
<input type="submit" >
</form>
Then use the JavaScript:
function getRadioValue(formName, groupName) {
var radioGroup = document[formName][groupName];
for (var i=0; i<radioGroup.length; i++) {
if (radioGroup[i].checked) {
return radioGroup[i].value;
}
}
return null;
}
By doing this, you avoid having to use a function that searches the entire document. It just searches first for the form, then within that form for controls with that same name. The problem here is that if you were to have a checkbox in the middle of the form with the same name, it could be returned instead of the correct radio value. If another type of control was thrown in with the same name, then it could cause an error. Both of these circumstances should probably be considered programmer error, but it wouldn't hurt for the function to be expanded to check for them, at some potential performance loss. Just change the line:
if (radioGroup[i].checked) {
to:
if (radioGroup[i].type=='radio' && radioGroup[i].checked) {
I'll bite for the jQuery answer
var selectedValue = $("input[name='radio_name']:checked").val();
var options = document.getElementsByName('myRadioButtons');
for(i = 0; i < options.length; i++)
{
var opt = options[i];
if(opt.type=="radio")
{
if(opt.checked)
{
}
}
}
<form name="myForm" id="myForm" action="">
<input type="radio" name="radioButton" value="c1">Choice 1
<input type="radio" name="radioButton" value="c2">Choice 2
</form>
<script>
var formElements = window.document.getElementById("myForm").elements;
var formElement;
var radioArray = [];
for (var i = 0, j = 0; i < formElements.length; i++) {
formElement = formElements.item(i);
if (formElement.type === "radio" && formElement.name === "radioButton") {
radioArray[j] = formElement;
++j;
}
}
alert(radioArray[0].value);
alert(radioArray[1].value);
</script>
$("input[type='radio'][name='xxxxx']:checked").val()
To get all radio buttons directly by name:
element.querySelectorAll("input[name='nameOfTheName']")
The querySelectorAll() method can be used to get elements of a certain type by name. There are advantages to using querySelectorAll compared to getElementsByName() in certain situations. If you use getElementsByName on anything other than document, you will get an error:
element_Name_Here.getElementsByName is not a function
But querySelectorAll() can be used on sub elements of the document. This is helpful when you want to get one element out of multiple elements that all have the same structure (Rows in a list). In that case, you might not want to try to give separate ID's to every row. In that situation, the function called can be passed this, get the parentNode and from the parent, search for a specific attribute. This avoids needing to search the entire document.
html
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
script
function getOnlyThisRowsRadios(thiz) {
var i,L,parentElement,radioButtons;
parentElement = thiz.parentNode;//Get the parent of the element
radioButtons = parentElement.querySelectorAll("input[name='nameOfTheName']");
console.log('radioButtons: ' + radioButtons)
L = radioButtons.length;
console.log('L: ' + L)
for (i=0;i<L;i++) {
console.log('radBttns[i].checked: ' + radBttns[i].checked)
radBttns[i].checked = false;//Un-check all checked radios
}
This definitely works if your name attribute is taken for something else.
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
console.log(radios[i])
}
}

Categories