jQuery radio array selector - javascript

I have radio buttons like:
<input type="radio" value="a" name="questions[0]">
<input type="radio" value="b" name="questions[0]">
<input type="radio" value="c" name="questions[0]">
<input type="radio" value="d" name="questions[0]">
<input type="radio" value="a" name="questions[1]">
<input type="radio" value="b" name="questions[1]">
<input type="radio" value="c" name="questions[1]">
<input type="radio" value="d" name="questions[1]">
How do I loop through this with jQuery? I want validate that a response has been given for each question. Thanks.
edit:
or is there even a way to get the length of the questions array?

$("#myForm input[type=radio]").each(function() {
//whatever you need
});

$('[name="questions[1]"]:checked').val() gives the checked value of question 1.
Or like below, get the checked value with the name:
$('input[type=radio]:checked').each(function() {
console.log($(this).val(), $(this).attr('name'));
});

You can do something like this:
var rgroups = [];
$('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;
$('#test').click(function () {
if ($('input:radio:checked').length < rgroups) alert('You must fill in all the fields.');
else alert("You're done!");
});
Fiddle Demo

Related

Verify all radio groups have a value checked using a generic selector

How to Verify all radio groups have at least 1 value selected using a generic selector and the .each() function.
All the examples I find require the id or name of the single radio options to be used not the group.
Try this:
const radios = {};
$('input[type="radio"]').each((i, e) => {
let $radio = $(e);
if ($radio.is(':checked')) {
radios[$radio.attr('name')] = $radio.val();
}
});
console.log(radios);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="radio" value="1" name="ri1">
<input type="radio" value="2" name="ri1" checked="checked">
<input type="radio" value="3" name="ri1">
<input type="radio" value="1" name="ri2">
<input type="radio" value="2" name="ri2">
<input type="radio" value="3" name="ri2" checked="checked">

How to push values in array using each()

I want to have a simple logic -
each loop runs for input radio and geting two value ie value of radio btton and name of radio button
Now the alert window only show result of last element
I want all the array result should be stored in mf
Name is comming dynamically
$("input[type=radio]:checked").each(function() {
var1 = $(this).val();
var2 = $(this).attr("name");
mf = [var2 + "_" + var1];
});
alert(mf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="r_1q_1" value="1" />A
<input type="radio" name="r_1q_1" value="1" />B
<input type="radio" name="r_1q_1" value="1" />B
<input type="radio" name="r_1q_1" value="1" />C
The issue you have is that you're redefining the value of mf in each iteration, hence it only holds the final value when the loop ends.
To fix this, use push() to add an element to the array:
var mf = [];
$("input[type=radio]:checked").each(function() {
var1 = $(this).val();
var2 = $(this).attr("name");
mf.push(var2 + "_" + var1);
});
console.log(mf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="r_1q_1" value="1" />A
<input type="radio" name="r_1q_2" value="2" checked="true" />B
<input type="radio" name="r_1q_3" value="3" />B
<input type="radio" name="r_1q_4" value="4" checked="true" />C
Also note that a better method to achieve what you need is to use map() to create the array directly from the jQuery object:
var mf = $("input[type=radio]:checked").map(function() {
return this.name + "_" + this.value;
}).get();
console.log(mf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="r_1q_1" value="1" />A
<input type="radio" name="r_1q_2" value="2" checked="true" />B
<input type="radio" name="r_1q_3" value="3" />B
<input type="radio" name="r_1q_4" value="4" checked="true" />C
Your redefining mf instead of adding stuff to it. You should do the following:
var mf = [];
$( "input[type=radio]:checked" ).each(function(){
var1 = $(this).val();
var2 = $(this).attr("name");
mf.push(var2+"_"+var1);
});
alert(mf) ;
First off, declare your variable mf as an array, then in your each loop use the .push() function to push data to it.
There is a Javascript function called .push() (Docs).
So what you do is that you define your mf array outside of the .each() and then for each iteration of the loop, you push the result into the mf array.
var mf = [];
$( "input[type=radio]:checked" ).each(function(){
var1 = $(this).val();
var2 = $(this).attr("name");
mf.push(var2+"_"+var1);
});
// mf = ["name1_val1", "name2_val2"]
var mf = [];
$("input[type=radio]:checked").each(function() {
var1 = $(this).val();
var2 = $(this).attr("name");
mf.push(var1)
mf.push(var2)
});
console.log(mf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="r_1q_1" value="1" checked/>A
<input type="radio" name="r_1q_1" value="1" />B
<input type="radio" name="r_1q_1" value="1" />B
<input type="radio" name="r_1q_1" value="1" />C
Use .push()
The push() method adds new items to the end of an array, and returns the new length.
I think this will work for you...!!
var mf = [];
$(document).on('click','input[type=radio]',function(){
if($(this).is(":checked")){
mf.push($(this).val()+"_"+$(this).attr("name")) ;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="r_1q_1" value="1" />A
<input type="radio" name="r_1q_1" value="2" />B
<input type="radio" name="r_1q_1" value="3" />B
<input type="radio" name="r_1q_1" value="4" />C
var studentList =[];
var emailAddresses=[];
$('table tr').each(function (i, row) {
var tr =$(row);
var chk= tr.find('input[type="checkbox"]').is(':checked')
console.log(chk)
if(chk){
emailAddresses.push(tr.find('.email').text())
studentList.push(tr.find('input[type="checkbox"]').prop('id'))
console.log(emailAddresses);
console.log(studentList);
}
});
DEMO

display the value of all selected radio buttons on a form

I have multiple radio buttons generated in a php loop which looks something like this
while(){
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' " onclick="return disp()""><span>'.$team1.'</span>
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()""><span>'.$team2.'</span>
<input type="radio" name="picks'.$x.'" value="draw" onclick="return disp()">
}
What I want to do
Display all selected radio buttons in a div on the bottom of page
My Code
var elmnts = document.getElementById("makePicksForm").elements
var lngth = document.getElementById("makePicksForm").length;
var div = document.getElementById("dispPicks");
for (var x = 0; x < lngth; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML = elmnts[x].value;
}
}
My Problem
Only the value of first selected radio button is displayed in div, other radio buttons are ignored
My Question
Any idea how I can modify my javascript to display the values of ALL selected radio buttons?
Since you've tagged your question with jQuery, here is a jQuery solution. Run the snippet to see it work:
$(document).ready(function () {
$(':radio').change(function (e) {
//clear the div
$('#dispPicks').html('');
//update the div
$(':radio:checked').each(function (ind, ele) {
$('#dispPicks').append($(ele).val() + '<br/>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="foo" value="foo1" />
<input type="radio" name="foo" value="foo2" />
<input type="radio" name="foo" value="foo3" />
<br/>
<input type="radio" name="bar" value="bar1" />
<input type="radio" name="bar" value="bar2" />
<input type="radio" name="bar" value="bar3" />
<br/>
<input type="radio" name="wow" value="wow1" />
<input type="radio" name="wow" value="wow2" />
<input type="radio" name="wow" value="wow3" />
<div id="dispPicks"></div>
You're using lngth in your for loop, but that's defined by getting an element by ID which should only be 1 element. Your loop will only run once that way...
Assuming the element with ID makePicksForm contains all your radio buttons, you need to get the length of the elements:
var elmnts = document.getElementById("makePicksForm").elements;
var div = document.getElementById("dispPicks");
for (var x = 0; x < elmnts.length; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML += elmnts[x].value;
}
}
Also, you need to add the value to the innerHTML property, using +=
as a side note: your PHP loop is creating duplicate ID's, which will result in failures in your javascript code if you need to reference the elements...
Another jQuery-Fiddle
<input type="radio" id="bob" name="boys" value="Bob"><label for="bob">Bob</label><br>
<input type="radio" id="jim" name="boys" value="Jim"><label for="jim">Jim</label><br>
<input type="radio" id="pete" name="boys" value="Pete"><label for="pete">Pete</label><br>
<input type="radio" id="mary" name="girls" value="Mary"><label for="mary">Mary</label><br>
<input type="radio" id="jane" name="girls" value="Jane"><label for="jane">Jane</label><br>
<input type="radio" id="susan" name="girls" value="Susan"><label for="susan">Susan</label>
<h3><span id="boy">?</span> and <span id="girl">?</span></h3>
$("input[name=boys]").click(function () {
$("#boy").text($(this).val());
});
$("input[name=girls]").click(function () {
$("#girl").text($(this).val());
});

How do I get the value of the checked radio button?

I have this simple script attached to a questionnaire and am having a problem getting the selected answer to show up in a textarea. Here is the script:
function check() {
var complete = 0;
var total = 0;
for (i=0;i<document.form.length;i++)
{
if (document.form.elements[i].checked == true && complete < 10) {
complete++;
total = (total) + (Math.round(document.form.elements[i].value));
}
}
if (complete >= 10) {
document.form.message.value = document.form.question1.value;
}
}
And here is the HTML:
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
I would like the value to be returned, but I am getting undefined. If I alter the line in the script that returns the text to:
document.form.message.value = document.form.question1;
I get [object NodeList]. I know I am missing something so simple but for the life of me I cannot find it.
Also, is it possible I can return the letters A through H along with the value? I know I can replace the value with the letters but need the numbers there for calculations.
My answer is going under the assumption that you would like the <textarea> to be populated with text similar to:
User answered 1 for Question A
User answered 2 for Question F
To get the A or F passed back, I needed to modify your html in the following way:
<input type="radio" value="1" name="question1" onclick="check(this, 'A')"> A<br />
<input type="radio" value="2" name="question1" onclick="check(this, 'B')"> B<br />
<input type="radio" value="3" name="question1" onclick="check(this, 'C')"> C<br />
<input type="radio" value="4" name="question1" onclick="check(this, 'D')"> D<br />
<input type="radio" value="1" name="question2" onclick="check(this, 'E')"> E<br />
<input type="radio" value="2" name="question2" onclick="check(this, 'F')"> F<br />
<input type="radio" value="3" name="question2" onclick="check(this, 'G')"> G<br />
<input type="radio" value="4" name="question2" onclick="check(this, 'H')"> H<br />
<textarea name="message"></textarea>
Otherwise, there's no actual connection between the letter and the radio input.
Anyway, here's what I done did:
I noticed that each group was repeating the same functionality, so I created a single Object Constructor:
var Answer = function () {
this.text = '';
};
this.text will contain the special answer string per group.
Now let's create the two answer group objects:
var answerOne = new Answer();
var answerTwo = new Answer();
Next comes the check() function where we pass the input element as well as it's associated answer character:
var check = function (_input, _question) {
if (_input.name === "question1") {
answerOne.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
if (_input.name === "question2") {
answerTwo.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
document.getElementsByName('message')[0].value = answerOne.text + answerTwo.text;
};
Now, as the user selects an answer, the appropriate answer group's string gets updated accordingly without affecting the other group's answer string.
Here's a jsfiddle with it working: http://jsfiddle.net/smokinjoe/uC76f/13/
Hope that helps!
You are referencing a form element in your script, do you define a form?
The answer seems to be addressed here
Attach event listener through javascript to radio button
Because it's a radio button, you need to loop through all values to find the one that has been selected. Something like this should work:
for (var i=0; i < document.form.question1.length; i++)
{
if (document.form.question1[i].checked)
{
document.form.message.value = document.form.question1[i].value;
}
}
}
Here you go the complete solution.
Couple of things went wrong in your code.
1. The way you get values from radio group. You need to iterate and find out which is checked
2. Setting value to textarea. You need to do getElemenetsByName[x]
<script>
function check() {
var complete = 0;
var total = 0;
var x = document.getElementsByTagName('input');
for(var k=0;k<x.length;k++){
if (x[k].checked && complete < 10) {
complete++;
total = total + Math.round(x[k].value);
}
}
(document.getElementsByName('message')[0]).value = total;
}
</script>
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
Not tested this, and as I don't know the name (or id) of your form(s), or indeed how many forms you have in your document, I have referenced your form by it's id.
function check() {
var complete = 0;
var total = 0;
var formId = 'EnterYourFormId'; // This could be passed as a paramter to the function instead (e.g. "function check(formId) {")
var _from = document.getElementById(formId); // The form could also be referenced by it's index, e.g. document.forms[0]
for (i=0; i < _from.elements.length; i++) {
if (_from.elements[i].type=='checkbox' && _from.elements[i].checked && complete < 10) {
complete++;
total = total + parseInt(_from.elements[i].value);
}
}
if (complete >= 10) {
_form.message.value = _form.question1.value;
}
}

How to find the value of a radio button with pure javascript?

<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue
Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.
In plain javascript (no jQuery), how can you get the actual selected option?
Try this:
var options = document.getElementsByName("colors");
if (options) {
for (var i = 0; i < options.length; i++) {
if (options[i].checked){
alert(options[i].value);
}
}
}
Would be so much easier with jQuery though... just saying.
I believe you will find it in the document.all collection:
var selectedColor = document.all["colors"];
plain javasript:
document.querySelector('input[name=colors]:checked').value;
you can try like this .....
This is example
<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1
<input name="choice" value="2" type="radio" />2
<input name="choice" value="3" type="radio" />3
<input name="choice" value="4" type="radio" />4
</form>
function to get the selected value
<script language="JavaScript">
function getRadioValue() {
for (index=0; index < document.frmRadio.choice.length; index++) {
if (document.frmRadio.choice[index].checked) {
var radioValue = document.frmRadio.choice[index].value;
break;
}
}
}
</script>
Well, they all have the same name. So naturally at least one of them has to be selected. Give them different ID's and try again.

Categories