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.
Related
I'm just trying to return true/false in one my my jquery methods depending on the check of a 2 radio buttons and if it's selected or not
I've tried several things but have not been able to get this right, it still submit the form without giving error that the buttons are not selected.
HTML Code
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" checked="" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" checked="true" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
Javascript
function checkOrderForm(frm) {
var paymentSelected = false;
var shippingSelected = false;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && frm.elements[i].checked) {
shippingSelected = true;
}
if (frm.elements[i].name == 'payment' && frm.elements[i].checked) {
paymentSelected = true;
}
}
if (!shippingSelected) {
alert(flow_no_shipping);
return false;
}
if (!paymentSelected) {
alert(flow_no_payment);
return false;
}
If I'm understanding your question correctly, you would only like this test to pass if BOTH of the radio buttons are checked. Currently, as long as one radio button in each group is checked, the code variable will be set to true, ignoring the state of the other radio button.
For example, if ONLY one of your shipping radio buttons was checked, the shippingSelected variable would be set to true and it would remain true.
A way to fix this is to begin with shippingSelected and paymentSelected set to true, and if one of the radio buttons are found to be unchecked, the variable will be set to false.
Here's an example:
var paymentSelected = true;
var shippingSelected = true;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && !frm.elements[i].checked) {
shippingSelected = false;
}
if (frm.elements[i].name == 'payment' && !frm.elements[i].checked) {
paymentSelected = false;
}
}
You can use $("#payment_1").checked to check whether the radio is checked or not. Similarly you could use other ID's to check whether they are selected or not.
Here is the fiddle:
https://jsfiddle.net/bf8bo43t/
Try below code,
HTML
<form method="post" name="frm_payment_types">
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<br />
<input type="submit" name="submit" onclick="return checkOrderForm();" />
</form>
Javascript
<script type="text/javascript">
function validateForm(){
var payment_1 = document.getElementById('payment_1');
var payment_2 = document.getElementById('payment_2');
var ECS_NEEDINSURE_1 = document.getElementById('ECS_NEEDINSURE_1');
var ECS_NEEDINSURE_2 = document.getElementById('ECS_NEEDINSURE_2');
if((payment_1.checked == true || payment_2.checked == true) && (ECS_NEEDINSURE_1.checked == true || ECS_NEEDINSURE_2.checked == true)){
return true;
}
else if(payment_1.checked == false && payment_2.checked == false){
alert("Please select Cash On Delivery or Credit Card / Debit Card.");
}
else if(ECS_NEEDINSURE_1.checked == false && ECS_NEEDINSURE_2.checked == false){
alert("Please select Home Delivery or Self-pickup.");
}
return false;
}
</script>
Does anyone have an idea why my JS function is not working/my price div isn't showing anything at all?
HTML:
<div id="variant">
<label><input type="radio" name="toggle" id="3"><span>A</span></label>
<label><input type="radio" name="toggle" id="12" checked="checked"><span>B</span></label>
<label><input type="radio" name="toggle" id="24"><span>C</span></label>
</div>
<br>
<div id="price"></div>
JS:
function setPrice() {
if (document.getElementById('3').checked) {
document.getElementById('price').innerHTML = "19,99€";
} else if (document.getElementById('12').checked) {
document.getElementById('price').innerHTML = "<<<";
} else (document.getElementById('24').checked) {
document.getElementById('price').innerHTML = "xxx";
}
}
An "else" condition doesn't take in a statement, it would be IF / ELSE IF that takes in statements. Please see updated code snippet!
function setPrice() {
if (document.getElementById('3').checked) {
document.getElementById('price').innerHTML = "19,99€";
} else if (document.getElementById('12').checked) {
document.getElementById('price').innerHTML = "<<<";
} else if (document.getElementById('24').checked) {
document.getElementById('price').innerHTML = "xxx";
}
}
setPrice();
<div id="variant">
<label><input type="radio" name="toggle" id="3" onClick="setPrice();"><span>A</span></label>
<label><input type="radio" name="toggle" id="12" onClick="setPrice();" checked="checked"><span>B</span></label>
<label><input type="radio" name="toggle" id="24" onClick="setPrice();"><span>C</span></label>
</div>
<br>
<div id="price"></div>
The error comes from two sources.
You aren't calling setPrice()
Your line else (document.getElementById('24').checked). There shouldn't be a condition if there isn't an if
I have a form which is similar like the one below:
<form id="myForm">
Question 1:<br>
<input type="radio" name="question1" value="Yes"> Yes
<input type="radio" name="question1" value="No"> No
<br>
Question 2:<br>
<input type="radio" name="question2" value="Yes"> Yes
<input type="radio" name="question2" value="No"> No
<br>
Question 3:<br>
<input type="radio" name="question3" value="Yes"> Yes
<input type="radio" name="question3" value="No"> No
<br>
<input type="submit" value="Submit" name="submit">
</form>
I want to get all the selected radio button values from all the questions using jQuery and if all values is equal to "yes", it will alert success else it will alert fail.
This is the jQuery I wrote:
$(document).ready(function(){
$("#myForm input[type=radio]:checked").each(function() {
var value = $(this).val();
});
});
You can check if you ever get no with radio checked then result is fail else success.
Live Demo
result = "success";
$("#myForm input[type=radio]:checked").each(function() {
if(this.value == "No" && this.checked == true)
{
result = "fail";
return false;
}
});
alert(result);
$(document).ready(function(){
var val=1;
$("#myForm input[type=radio]:checked").each(function() {
if($(this).val()=="No")
{
val=2;
}
});
if(val==1)
{
alert("Success !!");
}
else{
alert("Fail ");
}
});
$(document).ready(function(){
var no_found=false;
$("#myForm").submit(function(){
$(this).find("input[type=radio]:checked").each(function() {
var value = $(this).val();
if(value == "No")
no_found=true;
});
if(no_found==false){
alert("Success");
}
else{
alert("Fail");
}
});
});
Use this code:
$(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault();
var total = 0;
$('#myForm input[type="radio"]:checked').each(function() {
if ($(this).val() == 'Yes')
total++;
});
if (total == 3)
alert("Success");
else
alert("Fail");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
Question 1:
<br>
<input type="radio" name="question1" value="Yes" checked>Yes
<input type="radio" name="question1" value="No">No
<br>Question 2:
<br>
<input type="radio" name="question2" value="Yes">Yes
<input type="radio" name="question2" value="No" checked>No
<br>Question 3:
<br>
<input type="radio" name="question3" value="Yes">Yes
<input type="radio" name="question3" value="No" checked>No
<br>
<input type="submit" value="Submit" name="submit">
</form>
Try this code
$("#myForm").submit(function(){
var check = "Yes";
$(this).find("input[type=radio]:checked").each(function() {
var value = $(this).val();
if(value == "No")
check = "No";
});
alert(check)
});
You may try this as well:
http://codepen.io/anon/pen/JGeLMx
$('#myForm input[type="submit"]').on('click', function(e) {
e.preventDefault();
var result = true;
$('input[type="radio"]').each( function() {
var radio = $(this)[0];
if ( radio.value === 'Yes' && radio.checked === false )
result = false;
});
if ( result ) {
alert( 'Success!' );
} else {
alert( 'Fail!' );
}
});
Iterated all the radio buttons and if a single check on 'No' or none is selected at all it will fail, otherwise, it would mean all 'Yes' are checked - success.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('input[type="radio"]').change(function () {
var iCountTotal;
var iCountCkedYes;
iCountTotal = $('input[type="radio"]').length/2;
iCountCkedYes = $('input[type="radio"][value="Yes"]:checked').length;
if (iCountTotal != iCountCkedYes) {
alert('fail')
}
else {
alert('success')
}
});
});
</script>
<body>
<form id="myForm">
Question 1:<br>
<input type="radio" name="question1" value="Yes" checked="checked"> Yes
<input type="radio" name="question1" value="No"> No
<br>
Question 2:<br>
<input type="radio" name="question2" value="Yes"> Yes
<input type="radio" name="question2" value="No" checked="checked"> No
<br>
Question 3:<br>
<input type="radio" name="question3" value="Yes"> Yes
<input type="radio" name="question3" value="No" checked="checked"> No
<br>
<input type="submit" value="Submit" name="submit">
</form>
</html>
I want to make an online test, but i have some problems with the code below.
I want it to mark the correct and wrong answers, and show the score, when the button is pressed.
Now I have the following problem: I want the first switch statement to be only for the first group of radio buttons, the second switch statement for the second group of buttons, and so on.
How could I do that? When I run the code now, the colors change even though none of the radio buttons is checked, or when a button in only one of the groups is checked.
function showScore() {
var check;
var total = 0;
var yourmark = "your score is ";
switch (document.getElementById('q12').checked) {
case true:
total = total + 1;
document.getElementById('text1').style.color = "green";
break;
case false:
document.getElementById('text0').style.color = "red";
document.getElementById('text2').style.color = "red";
document.getElementById('text1').style.color = "green";
break;
}
switch (document.getElementById('q13').checked) {
case true:
document.getElementById('text0.1').style.color = "green";
total = total + 1;
break;
case false:
document.getElementById('text1.1').style.color = "red";
document.getElementById('text1.2').style.color = "red";
break;
}
alert(yourmark + total);
}
<input type="radio" name="question1" id="q11" value="false">
<text id="text0">Question 1-first option</text>
<br>
<input type="radio" name="question1" id="q12" value="true">
<text id="text1">Question 1- second option</text>
<br>
<input type="radio" name="question1" value="false">
<text id="text2">Question 1- third option</text>
<br>
<br>
<input type="radio" name="question2" id="q13" value="false">
<text id="text0.1">Question 1-first option</text>
<br>
<input type="radio" name="question2" id="q12" value="true">
<text id="text1.1">Question 1- second option</text>
<br>
<input type="radio" name="question2" value="false">
<text id="text1.2">Question 1- third option</text>
<br>
<button onclick="showScore();">Show my score</button>
Try this:
var questions = document.forms.myForm.getElementsByClassName('question');
document.getElementById('showScore').onclick = function showScore() {
var total = 0,
correct = 0;
for(var i=0; i<questions.length; ++i) {
var chosen = questions[i].querySelector(':checked');
if(chosen) {
questions[i].classList.add('show-score');
correct += chosen.value == 'true';
++total;
}
}
alert("Your score is " + correct + " out of " + total);
};
.question {
margin: 1em 0; /* Separation between questions */
}
.question > label:after { /* Line-break after each answer */
content: '';
display: block;
}
.question.show-score > input[value=true]+label {
color: green;
}
.question.show-score > input[value=false]+label {
color: red;
}
<form name="myForm">
<div class="question">
<input type="radio" name="question1" id="q-1-1" value="false">
<label for="q-1-1">Question 1 - first option</label>
<input type="radio" name="question1" id="q-1-2" value="true">
<label for="q-1-2">Question 1 - second option</label>
<input type="radio" name="question1" id="q-1-3" value="false">
<label for="q-1-3">Question 1 - third option</label>
</div>
<div class="question">
<input type="radio" name="question2" id="q-2-1" value="false">
<label for="q-2-1">Question 2 - first option</label>
<input type="radio" name="question2" id="q-2-2" value="true">
<label for="q-2-2">Question 2 - second option</label>
<input type="radio" name="question2" id="q-2-3" value="false">
<label for="q-2-3">Question 2 - third option</label>
</div>
<button id="showScore">Show my score</button>
</form>
Note those changes:
I have removed inline event listener from HTML, and added it using JS
I removed those ugly <br> and used CSS instead
I used <label> instead of invalid <text>. With <label>, you can also check a radio by clicking the text.
Instead of setting the color of correct/wrong answers with JS, I used CSS.
Well, ehr: group them. There's a lot wrong with your code and html. Id's are inconsistent, you are using inline event handlers, the code itself is bulky etc.
If you group the radiobuttons with a surrounding div, use consistent id's, labels instead of the <text> tag, leave the label-formatting to css and use querySelector[All], the code can be much shorter, really. Something like:
document.querySelector('body').addEventListener('click', showScore);
function showScore(e) {
var from = e.target || e.srcElement, fromtype = from.type;
if ( !(fromtype && /radio/i.test(fromtype)) ) { return true; }
var score = document.querySelectorAll('input:checked[value=true]').length;
// .. do stuff with [score]
}
It's demonstrated in this jsFiddle
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