How to find the value of a radio button with pure javascript? - 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.

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">

Combining a Javascript function

I'm trying to create a voting style system where the user selects 2 numbers from 2 separate groups of radio buttons.
I've been able to do this, however I don't feel it's as optimised as it should be:
http://jsfiddle.net/f54wpLzg/11/
function updateQuality() {
var quality = document.getElementsByClassName('quality');
for (var i = 0, length = quality.length; i < length; i++) {
if (quality[i].checked) {
totalQuality = parseInt(quality[i].value);
break;
}
}
qualityVal = totalQuality;
document.getElementById('totalQuality').innerHTML = qualityVal;
}
Is there anyway to combine the functions? I'd prefer not to have the
onclick="updateService();
On every single radio button as well...
You can both simplify and DRY up your code. Firstly add a data attribute to the containers to identify which element should be used to display the total:
<div id="quality" data-target="totalQuality">
<input type="radio" class="quality" name="quality" value="1" />
<input type="radio" class="quality" name="quality" value="2" />
<input type="radio" class="quality" name="quality" value="3" />
</div>
<div id="service" data-target="totalService">
<input type="radio" class="service" name="service" value="1" />
<input type="radio" class="service" name="service" value="2" />
<input type="radio" class="service" name="service" value="3" />
</div>
<br>
<span id="totalQuality">0</span>
<span id="totalService">0</span>
Then you can remove the onclick attribute and use jQuery to attach a single event handler to all the radios:
$('#quality input, #service input').change(function() {
var total = $(this).parent().data('target');
$('#' + total).html($(this).val());
});
Example fiddle
Since you are using jQuery you can remove the onclick attributes and do
$('#quality').on('change', '.quality', updateQuality);
$('#service').on('change', '.service', updateService);
in your script
To use a single method you could alter a bit your html to specify a target for each group (to display the value)
<div id="quality" data-target="#totalQuality">
<input type="radio" class="quality" name="quality" value="1">
<input type="radio" class="quality" name="quality" value="2" >
<input type="radio" class="quality" name="quality" value="3">
</div>
<div id="service" data-target="#totalService">
<input type="radio" class="service" name="service" value="1">
<input type="radio" class="service" name="service" value="2">
<input type="radio" class="service" name="service" value="3">
</div>
And then you can just do
function update() {
var target = $(this).closest('[data-target]').data('target');
$(target).text(this.value);
}
$('#quality, #service').on('change', 'input', update);
But it will not update global variables (if you required those)
you could just add a parameter inside the function then put a condition inside
something like this..
function updateVote(str) {
var data = document.getElementsByClassName(str);
for (var i = 0, length = data.length; i < length; i++) {
if (data[i].checked) {
totalCount = parseInt(data[i].value);
break;
}
}
val = totalCount;
if(str=="quality")
document.getElementById('totalQuality').innerHTML = val;
}
else{
document.getElementById('totalService').innerHTML = val;
}
on your html file..
onclick="updateVote('service')"
or
onclick="updateVote('quality')"

jQuery radio array selector

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

how to get only one radio button value in javascript

<input type="radio" name="red" value ="red" onclick="myFunction(this.value);"id="chkbx" /> Red<br>
<input type="radio" name="green" value ="green" onclick="myFunction(this.value);"id="chkbx" > green<br>
<input type="radio" name="yellow" value ="yellow " checked onclick="myFunction(this.value);"id="chkbx" > yellow<br>
<input type="radio" name="orange" value ="orange" onclick="myFunction(this.value);"id="chkbx" > orange<br>
<input type="radio" name="blue" value ="blue" onclick="myFunction(this.value);"id="chkbx" > blue<br>
<p id="demo"></p>
button onclick="myfunction(this.value)">My Choice</button>
<br><br>
<p id="demo"></p>
<script>
function myFunction(chkbx)
{
if(chkbx.checked)
{
chkbx.checked = false;
}
else
{
chkbx.checked = true;
}
The Thing is " I want to get the colour from radio button apply to a text in output screen(at a time one radio button would be select).What can i do. Please give some idea. i am new to javascript. I want in javascript only.
.Value will return you the value:
function myFunction(chkbx)
{
if(chkbx.checked)
{
alert(chkbx.value);
}
}
Give all the radio buttons in the group the same name.
Radio buttons allow the user to select only ONE of a predefined set of options. You define groups with the name property (radio buttons with the same name belong to the same group).
So to solve your issue, you can do as belows.
<p><input type="radio" name="color" value ="red"><i>Red</i></p>
<p><input type="radio" name="color" value ="green"><i>Green</i></p>
<p><input type="radio" name="color" value ="yellow" checked><i>Yellow</i></p>
<p><input type="radio" name="color" value ="orange"><i>Orange</i></p>
<p><input type="radio" name="color" value ="blue"><i>Blue</i></p>

display selected checkbox options on the page

was wondering if i could get a little help. I have 3 checkboxes and want to display the text before each checkbox back to the user.
<form id="extras" onchange="calculate()">
option 1<input type="checkbox" name="box" value="2000" id="snow" onchange="calculate()" checked><br>
option 2<input type="checkbox" name="box" value="500" id="water" onchange="calculate()" checked><br>
option 3<input type="checkbox" name="box" value="150" id="air" onchange="calculate()"><br><br>
</form>
so i can say you have selected option 1 and option 2 if they are both selected. Ive managed to to this for my dropdown using innerHTML but am unsure how to achieve this for the checkboxes. any ideas on how i can do this? thanks for any advice.
HTML
<form id="extras">
<label id="lbl_1">option 1</label><input type="checkbox" name="box" value="2000" id="1" onchange="calculate()"><br>
<label id="lbl_2">option 2</label><input id="2" type="checkbox" name="box" value="500" onchange="calculate()"><br>
<label id="lbl_3">option 3</label><input type="checkbox" name="box" value="150" id="3" onchange="calculate()"><br><br>
</form>
<span id="txt"></span>
Calculate function
function calculate()
{
document.getElementById("txt").innerHTML = "";
var checkBoxes = document.getElementsByName("box");
for(var i=0; i < checkBoxes.length;i++)
{
if(checkBoxes[i].checked)
{
document.getElementById("txt").innerHTML += document.getElementById("lbl_" checkBoxes[i].id).innerHTML
}
}
}
And JsFiddle
Here you go. I wrote this in jQuery, but you can convert it to vanilla JS.
http://jsfiddle.net/P2BfF/
Essentially you need to create labels for your checkboxes:
<label for='snow'>option 1</label>
Then based on checked, you can display the innerHTML of that element.
Here is my JS:
var checkboxes = $('#extras').find('input[type=checkbox]');
checkboxes.on('click',function() {
var selected = [];
checkboxes.each(function(idx,item) {
if (item.checked)
selected.push( $('label[for="' + item.id + '"]').html() );
});
return alert(selected);
});

Categories