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
Related
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 display an alert msg when all radio button checked to no? I only know check radio by individual only.
//I only know this method
$('#attraction1').change( function(){
if ($(this).is(':checked')) {
alert('Yes');
}
});
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br>
Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" name="individual" value="n" /> No
<br>
Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
In this case you should check something like this
$('#some_button').click( function(){
if ($('input[type="radio"][value="n"]:checked').length == 3) {
alert('Yes');
}
});
You can use a common class for all radio button with no value and a javascript array every method.
This line const radioNames = [...document.getElementsByClassName('no')]; will get all the radio button with no value ... is spread operator and will convert collection so that array method can be used on that collection.
This line item.addEventListener('change', checkIfAllNo) will attach event change to radio button with value no so that it checks the value for all other radio button
Array method every will return true if all the value in that array satisfies the condition.
So in this line radioNames.every(item => {return item.checked;}); if all the radio button with no value is checked then isAllFalse will be true & the alert will be triggered.
const radioNames = [...document.getElementsByClassName('no')];
function checkIfAllNo() {
const isAllFalse = radioNames.every(item => {
return item.checked;
});
if (isAllFalse) {
alert('All False')
}
}
radioNames.forEach((item) => {
item.addEventListener('change', checkIfAllNo)
})
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" class="no" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" class="no" name="individual" value="n" /> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" class="no" name="planBoard" value="n" /> No
In case you have an indeterminate number of inputs you can collect the values for every group and then check if all values match
$("input[type='radio']").change(function() {
// Extract all the radio group names
names = $.unique($('input[type="radio"]').map((v, e) => $(e).attr('name')))
// Collect the value for each group.
// Account for groups that are not selected yet
vals = $.map(names, function(name) {
return $(`input:radio[name="${name}"]:checked`).val() || 'undefined';
})
// Check if collected values match 'n'
console.log(vals.every(v => v == 'n'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" /> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" /> Yes
<input type="radio" id="individual2" name="individual" value="n" checked/> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
#ForeverTwoWheels
Please try this code,To Javascript radio group by button
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Radio Buttons</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="yes"> Yes
<input type="radio" name="choice" value="no"> No
<input type="button" id="btn" value="Show Selected Value">
</form>
<script>
const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
alert(selectedValue);
};
</script>
</body>
</html>
I hope this information will be usefull for you.
Thank you.
I have a list of check boxes with different values.
<input type="checkbox" value="55" id="myId">
<input type="checkbox" value="65" id="myId">
<input type="checkbox" value="75" id="myId">
<input type="checkbox" value="85" id="myId">
<input type="checkbox" value="95" id="myId">
When I'm getting those values using js that will take only value=55 only. It is due to the same id="myId"
var x = "";
$("input[type='checkbox']").change(fucntion(){
if(this.checked){
x = x+","+x;
}
});
When run that will load only 55 values like-: 55,55,55,55
Attribute id should be unique. You can use an array instead of string variable. Then simply add or remove item based on the check box status:
var x = [];
$("input[type='checkbox']").change(function(){
if(this.checked){
x.push(this.value);
}
else {
var index = x.indexOf(this.value);
x.splice(index, 1);
}
console.log(x.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" id="">55
<input type="checkbox" value="65" id="">65
<input type="checkbox" value="75" id="">75
<input type="checkbox" value="85" id="">85
<input type="checkbox" value="95" id="">95
First of all don't use multiple same ids on your page, id should be unique on entire page, try data attributes instead
$("input[type='checkbox']").change(function(){
var x = "";
$("[data-id=myId]").each(function(){
if(this.checked){
x = x + $(this).val() + ",";
}
});
console.log(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" data-id="myId">
<input type="checkbox" value="65" data-id="myId">
<input type="checkbox" value="75" data-id="myId">
<input type="checkbox" value="85" data-id="myId">
<input type="checkbox" value="95" data-id="myId">
If selection order isn't important can map() the checked values to new array every change
Your string concatenation approach doesn't take into account unchecking a previously checked input
$(':checkbox').change(function(){
var vals = $(':checkbox:checked').map(function(){
return this.value
}).get()
console.log(vals.join())
})
// insert values as text for demo
.wrap(function(){
return $('<label>',{text:this.value})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" >
<input type="checkbox" value="65" >
<input type="checkbox" value="75">
<input type="checkbox" value="85" >
<input type="checkbox" value="95" >
Note that ID's must be unique in a page
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
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;
}
}