Selecting radiobuttons using javascript. - javascript

I'm currently in the process of learning javascript. I want to create a dynamically quiz and now I want to check the value of my radiobuttons. This is my code:
HTML:
<div class="intro">
<h1>Welcome at my JavaScript Quiz</h1>
<br>
<span id="questions"></span>
<form name="radioAnswers">
<input type="radio" id="answer0" name="choice" value="a"><label for ="answer0" id="a0">Answer A</label>
<input type="radio" id="answer1" name="choice" value="b"><label for ="answer1" id="a1">Answer B</label>
<input type="radio" id="answer2" name="choice" value="c"><label for ="answer2" id="a2">Answer C</label>
<input type="radio" id="answer3" name="choice" value="c"><label for ="answer3" id="a3">Answer D</label>
</form>
<div class="buttons">
<button onclick="checkAnswers()">Submit answer</button>
</div>
And the checkAnswers function to check the answer. From what I understand the document.forms.radioAnswers.elements.choice will create an HTMLcollection. I want to iterate over this arraylike list and want to see which one is checked, and then put this into the answer variable. Like this:
function checkAnswers() {
var methods = document.forms.radioAnswers.elements.choice;
var answer;
for (var i = 0; i<methods.length; i++) {
if (methods[i].checked) {
answer = methods[i].value;
} else {
answer = "error"
}
} alert(answer);
}
When I run this it alerts "error" all the time. What am I missing?

You need to break the loop when you've found the answer, like this:
function checkAnswers() {
var methods = document.forms.radioAnswers.elements.choice;
var answer = "error";
for (var i = 0; i<methods.length; i++) {
if (methods[i].checked) {
answer = methods[i].value;
break;
}
}
alert(answer);
}
DEMO

Try this:
function checkAnswers() {
var answer="error";
if (document.getElementById('answer0').checked) {
answer = document.getElementById('answer0').value;
}
if (document.getElementById('answer1').checked) {
answer = document.getElementById('answer1').value;
}
if (document.getElementById('answer2').checked) {
answer = document.getElementById('answer2').value;
}
if (document.getElementById('answer3').checked) {
answer = document.getElementById('answer3').value;
}
alert(answer);
}
DEMO

Related

Uncaught SyntaxError: missing : after property id

I wanted to do a quiz. I thought I could do a var and whenever the right answer is clicked it gets to 1 and when you then press the button the correct answer is displayed. The problem is that no matter what I do it doesn't work.
var antwort = {
antwort = 0,
test: function() {
if (antwort === 0) {
document.getElementById("results").innerHTML = "That's right!";
} else {
document.getElementById("results").innerHTML = "That's wrong!";
}
},
antwort: function() {
antwort = 1
},
};
<input type="radio" name="q1" class="q">a<br>
<input type="radio" name="q1" class="q">b<br>
<input type="radio" name="q1" class="q" onclick="antwort()">c<br>
<input type="radio" name="q1" class="q">d<br>
<button id="submit" onclick="test()">Show Results</button>
<div id="results"></div>
You need
to selecet a different name for flag and function,
to use functions from the object,
to take better a boolean value as flag (which makes the comparison easier) and
to use this for addressing properties from the same object.
Inside the function, you could take a conditional (ternary) operator ?: for assigning the right message.
var antwort = {
antwort: false,
test: function () {
document.getElementById("results").innerHTML = this.antwort
? "That's right!"
: "That's wrong!";
},
richtigeAntwort: function () {
this.antwort = true;
}
};
<input type="radio" name="q1" class="q">a<br>
<input type="radio" name="q1" class="q">b<br>
<input type="radio" name="q1" class="q" onclick="antwort.richtigeAntwort()">c<br>
<input type="radio" name="q1" class="q">d<br>
<button id="submit" onclick="antwort.test()">Show Results</button>
<div id="results"></div>
Use === or == for comparison. I mean if (antwort === 0) or if (antwort == 0). Thank you.

About updating values in multiple check boxes

I have created multiple checkboxes using a script in an HTML file.
I want to updates the checkboxes using name based on a condition like the below.
Checkboxes[I].checked = true;
But it's throwing an error.
Can you please suggest a way to solve this issue out.
for this purpose I will try to answer you, I have two options, by class or tag name, may if you want to use Jquery its also nice. I prepare an example for you, I hope that this one helps you, greetings
function toggleA() {
var elm = document.getElementsByClassName('chx');
for(var i = 0; i < elm.length; i++) {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
function toggleB() {
var elm = $(".chx").prop("checked")
$(".chx").prop( "checked", !elm );
}
function toggleC() {
var elm = document.getElementsByTagName('input');
for(var i = 0; i < elm.length; i++) {
if(elm[i].type.toLowerCase() == 'checkbox') {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" onclick="toggleA()">Toggle A</button>
<button id="btn" onclick="toggleB()">Toggle B</button>
<button id="btn" onclick="toggleC()">Toggle C</button>
<br><br>
<label>
<input id="check-a" class = "chx" onchange="alert('Changed A!')" type="checkbox"> A
</label>
<br><br>
<label>
<input id="check-b" class = "chx" onchange="alert('Changed B!')" type="checkbox"> B
</label>
<br><br>
<label>
<input id="check-jq" class = "chx" onchange="alert('Changed JQ!')" type="checkbox"> JQ
</label>
<br><br>
<label>
<input id="check-c" class = "chx" onchange="alert('Changed C!')" type="checkbox"> C
</label>

HTML - Javascript on check

Okay first of all i have code like this
<input type="checkbox" class="css-checkbox" id="test1">
<input type="checkbox" class="css-checkbox" id="test2">
<input type="checkbox" class="css-checkbox" id="test3">
<input type="checkbox" class="css-checkbox" id="test4">
Now i modified it like this
<input type="checkbox" class="css-checkbox" id="test1" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test2" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test3" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test4" onclick="myFunction()">
And this is myfunction
function myFunction() {
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var checkBox = document.getElementById(testArr[i].value);
if (checkBox.checked == true){
Materialize.toast('I am a toast!', 4000)
}
}
}
What i am trying to do ?
I am trying to show a notice/Dialog that materialize.toast will show when checkbox with id test1 or test2 are checked. and doesn't do anything when test3 or test4 is selected. i hope anyone can help me with this.
I believe the below is what you are looking for.
First, add this as a parameter in the function used in the checkbox, that way you can trigger the clicked checkbox
And then in the function check if the clicked checkbox is checked, and have the special id, then do whatever you want
function myFunction(e) {
var testArr = ["test1", "test2"];
var chkId = $(e).attr("id");
if (e.checked == true && testArr.indexOf(chkId) !== -1) {
console.log("Materialize goes here!"); //Materialize.toast('I am a toast!', 4000)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="css-checkbox" id="test1" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test2" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test3" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test4" onclick="myFunction(this)">
You can try with the below code it will helps you.
function myFunction(id) {
var c = document.getElementById(id);
if((id=='test1' || id=='test2') && c.checked)
{
Materialize.toast('I am a toast!', 4000)
}
}
Issue with this line
var checkBox = document.getElementById(testArr[i].value);
It has to be
var checkBox = document.getElementById(testArr[i]).value;
Also to know if checkbox is checked, there is no need to get it's value
document.getElementById(testArr[i]).checked
will return state of checkbox
function myFunction() {
debugger;
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var checkBox = document.getElementById(testArr[i]);
if (checkBox.checked == true){
alert('I am a toast!');
}
}
}
removing value from document.getElementById(testArr[i]).value works for me
or you can directly check checkbox is checked or not using following function
function myFunction() {
debugger;
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var flag = document.getElementById(testArr[i]).checked;
if (flag){
alert('I am a toast!');
}
}
}
var checkBox = document.getElementById(testArr[i]);
This should solve your problem.

Validate radio button in javascript

function validate()
{
var payment = checkRadio();
if (payment == false)
{
alert("Please select one button")
}
}
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
else
{
return false;
}
}
}
The html code below creates the radio buttons for the client to select one of the payment methods
<P> Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
</P>
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
My problem is that when I execute this code and run it on chrome nothing happens. If someone could spot out where about I went wrong I would really appreciate it.
You need to surround your html code with <form>
<form>
Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
</form>
And in your javascript change the checkRadio to:
function checkRadio()
{
var payment = document.getElementsByName('payment');
var paymentType = '';
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
console.log(payment[i].value)
paymentType = payment[i].value;
}
}
return paymentType != '' ? true : false;
}
JSFiddle: https://jsfiddle.net/ttgrk8xj/16/
In your code you are checking only the first element is checked because you are returning from function in first iteration.
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
}
return false;
}

reorder radio button list

I have the below radio button list which is based on a multiple choice question, the information in the list will be added by a non technical user, I would like to know is there a method that i can use so the the list can be suffeled, each time the page has been loaded
<fieldset id="question1">
<div id="scenario">
QUESTION
</div>
<br/><br/>
<div>
Please select the correct answer:
</div>
<label>
<input type="radio" name="q1" value="correct"> ANSWER ONE</input>
</label>
<br/>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER TWO</input>
</label>
<br/>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER THREE</input>
</label>
<br/>
<br/>
<div id="result"></div>
<br/><br/>
<button type="button" id="answer" class="check" onclick="mark();" >Submit</button>
</fieldset>
try this...
You need to add all labels under one div.
<div class="list">
<label>
<input type="radio" name="q1" value="correct"> ANSWER ONE </input>
<br />
</label>
<label> <input type="radio" name="q1" value="wrong"> ANSWER TWO </input>
<br />
</label>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER THREE </input>
<br/>
</label>
</div>
Add following code in new shuffle.js file
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);
call to shuffle.js file Add following line of code in script tag to shuffle
<script>
$(document).ready(function(){
$( '.list label' ).shuffle();
});
</script>
if the answer are in array you can use this method
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
then you can call like this
var testArray = [1,2,3,4,5];
Shuffle(testArray);
for more details you can visti this link
What you need to do is:
Wrap all your answer labels in a div element, something like <div id="answers"></div>
Dispose of a <br /> elements between labels, instead specifying a style label {display: block;};
Apply following Javascript code
(with jQuery):
jQuery(function($){
var answers = $("#answers");
answers.html(
answers.find("label").sort(function(){
return Math.round(Math.random())-0.5;
})
);
});
And you're good to go.
Here's JSFiddle

Categories