How to access the value of a radio button - javascript

I am trying to access the value of a radio button using HTML and Javascript to make a simple quiz but it does not seem to be working. Here is my code:
function check() {
var a = document.getElementById("test").value
if (a === "one") {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test" value="one">1<br>
<input type="radio" name="one" id="test" value="two">2<br>
<input type="radio" name="one" id="test" value="three">3<br>
<button onclick="check()">Check</button>
</form>
It always says "Correct!" even when it is not. Does anyone know how to fix this?

Some points you are missing:
An id must be unique on the whole page
To check if a radio button is checked, use its checked attribute
function check() {
var two = document.getElementById("two");
if (two.checked) {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1>
<center>Simple Quiz</center>
</h1>
<br> 1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="one" value="one">1<br>
<input type="radio" name="one" id="two" value="two">2<br>
<input type="radio" name="one" id="three" value="three">3<br>
<button onclick="check()">Check</button>
</form>

First, you cannot have the same id on multiple elements. Make to give your elements a unique id and if you need to give them all the same style you could use class instead.
Instead of checking the value of the radio button, you should check whether the radio button is checked.
Take a look at the example below.
function check() {
if (document.getElementById('test2').checked) {
alert('correct');
} else {
alert('wrong');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
</head>
<body>
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test1" value="one">1<br>
<input type="radio" name="one" id="test2" value="two">2<br>
<input type="radio" name="one" id="test3" value="three">3<br>
<button onclick="check()">Check</button>
</form>
</body>
</html>

you should not define more than one element with the same id that's a bad practice, you could improve your code function check() {
for (elemnt of document.getElementByClassName('test') ) { if (element.checked ) alert('correct');
else alert ("incrrect");}}
Them in the html you can do this
<input type="radio" class="test" value="1">
<input type="radio" class="test" value="2">
<input type="radio" class="test" value="3">

Related

Radio Button failed sometimes to get value

$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.
Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.
To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>

How to display a div when 3 Radiobuttons from 3 questions checked?

I am trying to display 2 different div when the user answer 3 questions.
All questions have Yes and No answers which is shown by radio buttons.
I want to show div2 when 3 NO are given by the users. If ONLY ONE of the answers is Yes then the div1 must be shown.
this is the code:
<script type="text/javascript">
function display(e){
if(e.value == "yes"){
document.getElementById("hidediv1").style.display='block';
document.getElementById("hidediv2").style.display='none';
}
else if(e.value =="no"){
document.getElementById("hidediv2").style.display='block';
document.getElementById("hidediv1").style.display='none';
}
}
</script>
<form id="stu01" action="#" method="post">
<p>1. Q1?<br>
<input type="radio" name="sq01" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq01" value="no" onclick="display(this)">No
</p>
<p>2. Q2?<br>
<input type="radio" name="sq02" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq02" value="no" onclick="display(this)">No
</p>
<p>3. Q3?<br>
<input type="radio" name="sq03" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq03" value="no" onclick="display(this)">No
</p>
<div id="hidediv1" style="display:none">
</div>
<div id="hidediv2" style="display:none">
</div>
</form>
I hope that i understand ur request right..
JSFIDDLE DEMO
$('input[type="radio"]').click(function () {
var checkedNo = $('input[type="radio"]').filter(function () {
return $(this).is(":checked") && $(this).val() === "no";
});
if (checkedNo.length === 3) {
$('#hidediv1').show();
$('#hidediv2').hide();
} else {
$('#hidediv2').show();
$('#hidediv1').hide();
}
});
Full version:
<!DOCTYPE html>
<html>
<head>
<title>Form Radio Button</title>
</head>
<body>
<form id="stu01" action="#" method="post">
<p>1. Q1?<br>
<input type="radio" name="sq01" value="yes">Yes
<input type="radio" name="sq01" value="no">No
</p>
<p>2. Q2?<br>
<input type="radio" name="sq02" value="yes">Yes
<input type="radio" name="sq02" value="no">No
</p>
<p>3. Q3?<br>
<input type="radio" name="sq03" value="yes">Yes
<input type="radio" name="sq03" value="no">No
</p>
<div id="hidediv1" style="display:none">
No!
</div>
<div id="hidediv2" style="display:none">
Yes!
</div>
</form>
<script src="http://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b‌​8=" crossorigin="anonymous"></script>
<script type="text/javascript">
$('input[type="radio"]').click(function () {
var checkedNo = $('input[type="radio"]').filter(function () {
return $(this).is(":checked") && $(this).val() === "no";
});
if (checkedNo.length === 3) {
$('#hidediv1').show();
$('#hidediv2').hide();
} else {
$('#hidediv2').show();
$('#hidediv1').hide();
}
});
</script>
</body>
</html>
Use onChange event listener, update a variable status, check when it is 3, append your div

Change submit button text based on radio-button value

How to change submit button text based on which radio-button is active?
Here is my code, but it does not work. It changes text only once.
I have two radio-buttons:
<input type="radio" name="build-team" class="choose" value="build" /> Yes
<input type="radio" name="build-team" class="choose" value="show" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
And I have script:
$(document).on('click', '.choose', function() {
var target = $('.show-result');
if ($(this).attr('checked') == 'checked') {
target.html(target.data('chooseyes'));
}
else {
target.html(target.data('chooseno'));
}
})
JSFiddle example
$(document).on('click', '.choose', function() {
var target = $('.show-result');
target.html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="build-team" class="choose" value="Yes" /> Yes
<input type="radio" name="build-team" class="choose" value="No" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
$('.opt').click(function(){
$('#button').html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="opt" name="opt" type="radio" value="Yes" checked="checked">Yes
<input class="opt" name="opt" type="radio" value="No">No
<button id="button" type="submit">Yes</button>
This is the easiest answer, no added attributes, only clean HTML + jQuery, it is also important to realize that there must always be a radio selected/checked by default, if not, you would have to validate the field and validating a radio is not cool haha :) have a nice day!

Display value of checkbox in textarea

I have here a code that will display the value of the checkbox when checked. My problem is I don't know how I will add up all the numbers, that when I checked a checkbox the number or value will display automatically to the text area and when I checked another checkbox it will add up to the first checkbox that I checked and when I checked another checkbox it should also add up from the first two checkbox. How will I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function add_sub(el)
{
if (el.checked)
{
var total = el;
total.form.elements['type'].value+=el.value;
}
else
{
var re=new RegExp('(.*)'+el.value+'(.*)$');
el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2');
}
}
</script>
</head>
<body>
<form name="form1" method=post>
<textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</form>
</body>
Please check this fiddle if this is what you meant:
http://jsfiddle.net/zyfmt4at/5/
this is the script:
var currNum = 0;
var txtArea = document.getElementById("txtArea");
var form = document.getElementById("mainForm");
function add_sub(el){
debugger;
if (el.checked)
{
currNum += parseInt(el.value,10);
}
else
{
currNum -= parseInt(el.value,10);
}
txtArea.value = currNum;
}
form.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
add_sub(ev.target);
}
},false);
this is the HTML:
<body>
<form id="mainForm" name="form1" method=post>
<textarea id="txtArea" name="type" rows="5" cols="35" onclick="this.focus();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4"><label>4</label>
</form>
</body>
The solutions proposed above are based on an assumption that the checkbox values are numbers, in case you are in need of string values. You may suggest this.
function add_sub(el)
{
var cbs = document.getElementById('checkboxes').getElementsByTagName('input');
var textareaValue = '';
for (var i = 0, len = cbs.length; i<len; i++) {
if ( cbs[i].type === 'checkbox' && cbs[i].checked) {
textareaValue += cbs[i].value + ' ';
}
}
document.getElementById('textarea').value = textareaValue;
}
and
<textarea id="textarea" name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<div id="checkboxes">
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</div>
And the working plunker:
http://plnkr.co/edit/HWHRsBn7s7vJ9KI4UauU
Some tips:
Don't listen to click events to detect changes in checboxes. They can change in other ways, e.g. with the keyboard. You can listen to change events instead.
Don't use event handler content attributes in the HTML source. Add event listeners using JS.
Don't add the same event listener to all events. Delegate it to a common ancestor instead.
br elements are ugly. Better use display: block.
var sum = 0,
form = document.forms.form1,
text = form1.elements.type;
text.addEventListener('focus', text.select.bind(text));
form.addEventListener('change', function(e) {
if(e.target.type == 'checkbox') {
sum += e.target.value * (e.target.checked ? 1 : -1);
text.value = sum;
}
});
label { display: block; }
<form name="form1" method="post">
<textarea name="type" rows="5" cols="35">0</textarea>
<label><input type="checkbox" name="mis1" id="id1" value="1">1</label>
<label><input type="checkbox" name="mis2" id="id2" value="2">2</label>
<label><input type="checkbox" name="mis6" id="id3" value="3">3</label>
<label><input type="checkbox" name="mis6" id="id4" value="4">4</label>
</form>

Converting radiobuttons into checkboxes with javascript

I've a set of radio buttons and a checkbox on the page like below
<html>
<head>
<title>Languages</title>
<script type="text/javascript">
</script>
</head>
<body>
<span>What languages do you know?</span>
<form action="">
<div id="controlArea">
<input type="radio" name="lanRadio" value="radioRussian"><label for="radioRussian">Russian</label><br />
<input type="radio" name="lanRadio" value="radioEnglish"><label for="radioRussian">English</label><br />
<input type="radio" name="lanRadio" value="radioSpain"><label for="radioRussian">Spain</label><br />
<input type="radio" name="lanRadio" value="radioFrench"><label for="radioRussian">French</label><br />
<input type="checkbox" name="checkIn" value="CheckMore"><label for="CheckMore">More than 1</label><br />
</div>
</form>
</body>
What I want to do is, if a user checks the "More than 1" checkbox, all radio buttons must turn into checkboxes and users must be able to check more options. If the user unchecks the checkbox, all the checkboxes must turn back into a set of radio buttons. When changing radiobuttons to checkboxes, the selected radio button must become the checked checkbox.
You could do something like this :
function morethan(cbox) {
// setup new state
var state = "radio";
if (cbox.checked) {
state = "checkbox";
}
// get all by name and change state
var radios = document.getElementsByName('lanRadio');
for (i = 0; i < radios.length; i++) {
radios[i].type = state;
}
}​
You need to add an onclick handler to your checkbox :
<input type="checkbox" name="checkIn" onclick="morethan(this)" value="CheckMore">
Example here
Try this . Just copy and paste my code
<html>
<head>
<title>Languages</title>
<script type="text/javascript">
if(document.getElementById("radio1").type=="radio")
{
document.getElementById("radio1").type="checkbox";
document.getElementById("radio2").type="checkbox";
document.getElementById("radio3").type="checkbox";
document.getElementById("radio4").type="checkbox";
}
else
{
document.getElementById("radio1").type="radio";
document.getElementById("radio2").type="radio";
document.getElementById("radio3").type="radio";
document.getElementById("radio4").type="radio";
}
</script>
</head>
<body>
<span>What languages do you know?</span>
<form action="">
<div id="controlArea">
<input type="radio" id="radio1" name="lanRadio" value="radioRussian"><label for="radioRussian">Russian</label><br />
<input type="radio" id="radio2" name="lanRadio" value="radioEnglish"><label for="radioRussian">English</label><br />
<input type="radio" id="radio3" name="lanRadio" value="radioSpain"><label for="radioRussian">Spain</label><br />
<input type="radio" id="radio4" name="lanRadio" value="radioFrench"><label for="radioRussian">French</label><br />
<input type="checkbox" name="checkIn" value="CheckMore" onchange="fnc()"><label for="CheckMore">More than 1</label><br />
</div>
</form>
</body>

Categories

Resources