how to get checked radio button value in javascript - javascript

I have some set of radio button. I am trying to get checked radio button value using java script. But I got the error of uncaught id. I do the following code in html 5. I am not getting the value.
function timeout()
{
if (document.getElementById["RadioButton1"].checked)
{
choice = document.getElementById["RadioButton1"].value;
alert('choice');
}
if (document.getElementById["RadioButton2"].checked)
{
choice = document.getElementById["RadioButton2"].value;
alert('choice');
}
if (document.getElementById["RadioButton3"].checked)
{
choice = document.getElementById["RadioButton3"].value;
alert('choice');
}
if (document.getElementById["RadioButton4"].checked)
{
choice = document.getElementById["RadioButton4"].value;
alert('choice');
}
var c = document.getElementById("label1").value;
}

If you use the same name(in same radio button group) for all radio buttons like this
<input type="radio" id="RadioButton1" name="radio_group" value="1"/>
<input type="radio" id="RadioButton2" name="radio_group" value="2"/>
<input type="radio" id="RadioButton3" name="radio_group" value="3"/>
you can get the selected(checked radio button value ) using jQuery,in one line.
var Val = $("input[name=radio_group]:checked").val();

A set of radio buttons should all have the same name. So get the set, find the checked one and read its value:
function getValue(name) {
var rbs = document.getElementsByName(name);
for (var i=0, iLen=rbs.length, i<iLen; i++) {
if (rbs[i].checked) {
return rbs[i].value;
}
}
}
If the controls are in a form (which the usually are) and you have a reference to the form, you can get the set using:
var rbs = formRef[name];

$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#result').html(result.val()+" is Checked");
}else{
$('#result').html(" No radio button is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>

The major problem visible from your code is a syntax error.
document.getElementById is a method and not an object, so you should call it with parens:
// --------------------v--------------v
document.getElementById("RadioButton1").value

This is ans for #yogi comment(
how we can implement same for checkboxes?)
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#result').html(resultstring);
}else{
$('#result').html(" No checkbox is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>

Related

Javascript: value of radio button to empty blank square box using innerHTML

I'm having trouble display value of radio button
when I click on the radio buttons,
I want to see all the values of buttons in the box.
its shows values on the console but in the box, it only shows 'carrot' which is one of ingredients in the array.
function mixRecipeBox(){
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
console.log(mixIngredients[i].value);
document.getElementById('mixbox').innerHTML = mixIngredients[i].value;
}
}
You are replacing all data of mixbox in each loop. use this to
append data.
You forgot {} for if block
Empty mixbox on start of function.
use checkbox instead of radio so user can discard choice.
function mixRecipeBox(){
document.getElementById('mixbox').innerHTML=""
var currentHTML;
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
{
console.log(mixIngredients[i].value);
currentHTML= document.getElementById('mixbox').innerHTML;
document.getElementById('mixbox').innerHTML = currentHTML+mixIngredients[i].value;
}
}
}
<input type="checkbox" value="1" onchange="mixRecipeBox()">
<input type="checkbox" value="2" onchange="mixRecipeBox()">
<input type="checkbox" value="3" onchange="mixRecipeBox()">
<input type="checkbox" value="4" onchange="mixRecipeBox()">
<div id="mixbox"></div>
Loop over each radio element and assign a click event handler.
The radio button click handler first clears the mixbox, then loops over each radio element and puts checked radio button values in the mixbox.
<div id="rads">
<input type="radio" value="one" />1
<input type="radio" value="two" />2
<input type="radio" value="three" />3
</div>
<div id="mixbox"></div>
<script>
var rads = document.querySelectorAll('#rads input[type=radio]');
var mixbox = document.getElementById('mixbox');
Array.prototype.forEach.call(rads, function (elem) {
elem.addEventListener('click', function (evt) {
mixbox.innerHTML = '';
Array.prototype.forEach.call(rads, function (ele) {
if ( ele.checked ) { mixbox.innerHTML += ele.value + '<br>'; }
})
})
})
</script>
JSFiddle

How to get the text of the checked radio button? [duplicate]

This question already has answers here:
How do I get the label of the selected radio button using javascript
(3 answers)
Closed 8 years ago.
I have a group of radio buttons and want to get the checked radio button, then alert the text, not only the value of it. To explain more, when the user clicks the first radio button, and then submits the form, I want the browser to alert "Desktop Case." And I want to achieve this without jQuery.
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
The following works for your example. It uses CSS selectors to target the checked input. Based on its id, the appropriate label is found:
function update_order_onclick() {
var value= 'Nothing selected',
selected= document.querySelector('input[name="rad_case"]:checked'),
selection= document.querySelector('#selection');
if(selected) {
value= document.querySelector('label[for="'+selected.id+'"]').innerHTML;
}
selection.innerHTML= value;
}
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<br>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<br>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<br>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
<div id="selection"></div>
First, we create a function to loop through the radio buttons group we have, and checks if it is checked or not.
function get_radio_val(form, name)
{
var val;
var radios = form.elements[name];
for (var i =0; i < radios.length; i++)
{
if (radios[i].checked)
{
val = radios[i];
break;
}
}
return val;
}
Then we write the function that will be executed on onclick event.
function update_order_onclick()
{
var val = get_radio_val(document.form1, 'rad_case');
var val_id = val.id;
var selector = 'label[for=' + val_id + ']';
var label = document.querySelector(selector);
var label_text = label.innerHTML;
alert(label_text);
}
The thing that helped us here, is that the label for attribute has to be the same value as the radio button id and that's how we selected it in the function above.
simply do the following:
var checked = document.querySelector('input:checked');
var id = checked?checked.id:'bla';
var lab = document.querySelector('label[for='+id+']');
var lab_text = lab?lab.textContent:'';

set of radio button validation using Javascript

I am trying to validate 2 sets of radio button using Javascript. It is working with one set but not when I add another radio set (secondtime visitor). Here is my code:
HTML:
<form name="form1" action="#" method="post">
First time visitor?:<br/>
<label for="s1">Yes</label>
<input type="radio" id="radio1" name="firsttime" value="1"/>
<br/>
<label for="s2">No</label>
<input type="radio" id="radio2" name="firsttime" value="2"/>
<br/>
Second time visitor?:<br/>
<label for="s1">Yes</label>
<input type="radio" id="radio1" name="secondTime" value="1"/>
<br/>
<label for="s2">No</label>
<input type="radio" id="radio2" name="secondTime" value="2"/>
<br/>
<button type="submit" name="nextBTN" onclick="return validateForm();">Next</button><br/>
</form>
And Javascript code:
function validateForm() {
var radios = document.getElementsByName("firsttime");
var radios2 = document.getElementsByName("secondtime");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
var j = 0;
while (!formValid && i < radios2.length) {
if (radios2[j].checked) formValid = true;
j++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}
At first glance, I can see that in your second while loop, you still check the radios variable instead of the radios2 variable.
You also used the i variable instead of j in the second loop. And you weren't consistent with the capitalization of secondTime (vs secondtime).
Here's a working version of your code:
http://jsfiddle.net/8edCn/
EDIT: Updated version per your comment: http://jsfiddle.net/8edCn/2/

jquery: how to check if all radio buttons in a div are selected

my html looks like this
<div id="div1">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
radio buttons are dynamically generated on my html so in that div i don't know how many radio buttons i have.
i want to make sure that the user will select a value for each one of them before he submits the form, how can i check that all radio buttons inside my div has a value checked?
Thank you
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Demo: http://jsfiddle.net/yFaAj/15/
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution here http://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
return false;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<br/>Q2
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<br/>Q3
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn" type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
return true;
return false;
});
Try this one:
$('input:radio', $('#div1')).each(function() {
if(name && name == $(this).attr('name'))
return true; // Skip when checking the same element name.
name = $(this).attr('name');
if(! $('input:radio[name="' + name + '"]:checked').length) {
alert('Oops, you missed some input there.. [' + name + ']');
return false;
}
});
It will loop through every radio button to check for checked radio & will break as soon it found non-checked radio group (first error found). But if you prefer to get all the errors (not only the first error found), just remove return false.
Try this:
function check(){
var allCheck = true;
if($("#div1 :radio:checked").length==0){
allCheck=false;
}
$("#div1 :radio").each(function(){
for(var i=0;i<$("#div1 :radio:checked").length;i++)
if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name"))
break;
else if(i==$("#div1 :radio:checked").length-1)
allCheck = false;
});
return allCheck;
}
This will work:
if($("#div1").children("input:radio:checked").size() == 3)
{
alert('three inputs were checked');
}

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources