I am having a problem passing a varible from one function to another and I defined the variable OUTSIDE of a function so as far as I know, It Should be Global..
Here are the functions along with the RadioButtons that I pulled the value from.
<!-- Here is the Form Part -->
<form method="post" action="#pizzatoppingtypes" name="pizzatoppings" id="pizzatoppingsform">
<div id="main">
<div class="example">
<div>
<input id="plainpizza" type="radio" name="pizzatoppings" value="0" checked="checked"><label style="color:black" for="plainpizza"><span><span></span></span>Plain Pizza</label>
</div>
<div>
<input id="onepizza" type="radio" name="pizzatoppings" value="1"><label style="color:black" for="onepizza"><span><span></span></span>1 Topping</label>
</div>
<div>
<input id="twopizza" type="radio" name="pizzatoppings" value="2"><label style="color:black" for="twopizza"><span><span></span></span>2 Toppings</label>
</div>
<div>
<input id="threepizza" type="radio" name="pizzatoppings" value="3"><label style="color:black" for="threepizza"><span><span></span></span>3 Toppings</label>
</div>
<div>
<input id="fourpizza" type="radio" name="pizzatoppings" value="4"><label style="color:black" for="fourpizza"><span><span></span></span>4 Toppings</label>
</div>
<div>
<input id="fivepizza" type="radio" name="pizzatoppings" value="5"><label style="color:black" for="fivepizza"><span><span></span></span>5 Toppings</label>
</div>
<div>
<input id="sixpizza" type="radio" name="pizzatoppings" value="15"><label style="color:black" for="sixpizza"><span><span></span></span>6 Or More Toppings</label>
</div>
<div>
<input id="tacopizza" type="radio" name="pizzatoppings" value="8"><label style="color:black" for="tacopizza"><span><span></span></span>Taco Pizza</label>
</div>
</div>
<div class="one_third_last">
<label> </label>
<input class="contact_button button" type="submit" name="submit" id="pizzatoppingsform" value="Next" />
</div>
</div>
</form>
<!--Form End-->
<!--Here is the JS-->
<script type="text/javascript">
function getRadioVal(form, name) {
// get list of radio buttons with specified name
var radios = form.elements[name];
// loop through list of radio buttons
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked ) { // radio checked?
var vam = radios[i].value; // if so, hold its value in val
break; // and break out of for loop
}
}
return vam; // return value of checked radio or undefined if none checked
}
</script>
<script type="text/javascript">
$(document).ready(function () {
var val; //Defined Here So That It Should Be Able To Be Used On Both Functions Below.
<!--Figures Out How Many Toppings The Person Wants-->
$('#pizzatoppingsform').submit(function( event ) {
val = getRadioVal(this, 'pizzatoppings');
alert(val); //Used Just To Verify The Value Is Being Stored.
});
<!--Limits How Many Check Boxes A Person Can Select Based On How Many Toppings They Selected. -->
$("input[name='toppingtypes']").change(function () {
var maxAllowed = Number(val); //If I Use An Actual Number Such As 2 Instead of This val Variable, This Function Works.
var cnt = $("input[name='toppingtypes']:checked").length;
if (cnt > maxAllowed) {
$(this).prop("checked", "");
alert('You can select a maximum of' + maxAllowed + ' Toppings');
}
});
});
</script>
Note: This last Function here where I have "var maxAllowed = Number(val);", When I insert a number instead for example 2, that function works. So as far as I know, the problem resides in the variable not being transferred over even though I declared it outside of a function.
Here Is my Git Hub Repository if you want to see more of the code.
https://github.com/dhierholzer/onlineordering
Thanks again.
var val = getRadioVal(this, 'pizzatoppings');
by using var you're no longer referencing the global val--you're using a local with the same name.
Related
Sumary: I am looking for away to add two seperate getElementbyId and a submit button to an If Statment in order to make it run.
HTML Example:
<form>
<div>
<fieldset id="group1">
<input type="radio" name="type" id="h" value="1111" onclick="func2();" />0 Human</br>
<input type="radio" name="type" id="r" value="2222" onclick="func2();" />1 Robot</br>
<input type="radio" name="type" id="a" value="3333" onclick="func2();" />2 Animal</br>
</fieldset>
</div>
<div>
<fieldset id="group2">
<input type="radio" name="type" id="c" value="1111" onclick="func2();" />4 Jerry</br>
<input type="radio" name="type" id="b" value="2222" onclick="func2();" />5 Xr10Zbot</br>
<input type="radio" name="type" id="z" value="3333" onclick="func2();" />6 Girrafe</br>
</fieldset>
<p><input style="width: 60px;" type="submit" name="type" id="f" class="7" value="submit" onclick="func()2;" /></p </div>
</form>
JavaScript Example:
<script>
function func2()
{
if(document.getElementById("h").checked)
// I want for the if statment to require you to also have to check c and click submit to run
{
var val = document.getElementById("h").value;
alert(val);
}
else if(document.getElementById("r").checked)
{
var val = document.getElementById("r").value;
alert(val);
}
else if(document.getElementById("a").checked)
{
var val = document.getElementById("a").value;
alert(val);
}
}
</script>
What I need the if statment to run:
Make it to wher you have to click two radio buttons and submit to run the alert
if(document.getElementById("h").checked) + (document.getElementById("c").checked) + (document.getElementById("f"))
I don't fully understand what you want to do. I hope my solution will help you.
Issue 1
There is a typo in the submit button.
❌NG onclick="func()2;"
✅OK onclick="func2();"
Issue 2
Radio buttons with the same name attribute belong to one group. Therefore, only one of the six buttons can be turned on. One of the buttons in #group1 and one of #group2 are not turned on at the same time. Change name.
For example,
<fieldset id="group2">
<input name="type2">
<input name="type2">
<input name="type2">
</fieldset>
Issue 3
I think it is a bit difficult to use func2() for all buttons including the submit button. I recommend making another function for it.
My solution
This JS doesn't work properly here on the embed snippet. Please copy, paste and run it on an actual editor such as Visual Studio Code.
// Get DOMs
var elementC = document.getElementById('c');
var submitButon = document.getElementById('f');
// Get #group1 radio buttons at once
var group1Buttons = document.querySelectorAll('#group1 [type="radio"]');
// These are needed in If statements
// var elementH = document.getElementById('h');
// var elementR = document.getElementById('r');
// var elementA = document.getElementById('a');
function func2(e) {
e.stopPropagation();
// You may use this If statement
// if (elementH.checked) {
// alert(elementH.value);
// } else if (elementR.checked) {
// alert(elementR.value);
// } else if (elementA.checked) {
// alert(elementA.value);
// }
// I prefer this one because it's shorter.
alert(this.value);
}
function func3(e) {
e.stopPropagation();
if (!elementC.checked) {
e.preventDefault(); // Stop submitting
alert(`You need to check ${elementC.getAttribute('data-text')}!!`);
}
}
// When one of the radio buttons is clicked, executes func2()
group1Buttons.forEach(radio => radio.addEventListener('click', func2, false));
// When the submit button is clicked, executes func3()
submitButon.addEventListener('click', func3, false);
<form>
<div>
<!-- Removed onClick="func2()" -->
<!-- Added required to one of radio buttons -->
<fieldset id="group1">
<input type="radio" name="type" id="h" value="1111" required />0 Human</br>
<input type="radio" name="type" id="r" value="2222" />1 Robot</br>
<input type="radio" name="type" id="a" value="3333" />2 Animal</br>
</fieldset>
</div>
<div>
<!-- Removed onClick="func2()" -->
<!-- Added required to one of radio buttons -->
<!-- Change name: type => type2 -->
<!-- Added data-text attribute -->
<fieldset id="group2">
<input type="radio" name="type2" data-text="4 Jerry" id="c" value="1111" required />4 Jerry</br>
<input type="radio" name="type2" id="b" value="2222" />5 Xr10Zbot</br>
<input type="radio" name="type2" id="z" value="3333" />6 Girrafe</br>
</fieldset>
<!-- Removed onClick="func2()" -->
<p><input style="width: 60px;" type="submit" name="type" id="f" class="7" value="submit" /></p>
</div>
</form>
I am trying to validate multiple groups of radio buttons with pureJS. Basically my client has a group of around 50 questions, and each one has 4 radio buttons that can be used to pick 1 of 4 answers.
They do not want to use jQuery, but pureJS, I have gotten the following to work when there is just one question, but not when there is multiples, any help would be appreciated.
document.getElementById("submit_btn").addEventListener("click", function(event){
var all_answered = true;
var inputRadios = document.querySelectorAll("input[type=radio]")
for(var i = 0; i < inputRadios.length; i++) {
var name = inputRadios[i].getAttribute("name");
if (document.getElementsByName(name)[i].checked) {
return true;
var all_answered = true;
} else {
var all_answered = false;
}
}
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
event.preventDefault();
}
});
The questions are all laid out like this -
<div class="each-question">
<div class="unanswered-question">
<div class="question-text">
<div class="number">33</div>
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label"> Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label"> Not Interested</label>
</div>
</div>
</div>
This is the original jQuery used by the client which now has to be in pureJS
jQuery(document).ready(function () {
jQuery("#question_list").submit(function () {
var all_answered = true;
jQuery("input:radio").each(function () {
var name = jQuery(this).attr("name");
if (jQuery("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
return false;
}
});
});
Not sure if it's just an issue with the copy, but you have a return true in your for loop which will cause the entire function to simply return true if just one is answered. Removing that would help.
Ignoring that though, your solution is a bit unwieldy, as it'll loop through every single input on the page individually and will mark it false if not every radio button is unchecked.
Here is a different approach. Basically, get all of the radio buttons, then group them into arrays by question. Then, loop through each of those arrays and check that within each group, at least one is answered.
document.querySelector('form').addEventListener('submit', e => {
// Get all radio buttons, convert to an array.
const radios = Array.prototype.slice.call(document.querySelectorAll('input[type=radio]'));
// Reduce to get an array of radio button sets
const questions = Object.values(radios.reduce((result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }), {}));
// Loop through each question, looking for any that aren't answered.
const hasUnanswered = questions.some(question => !question.some(el => el.checked));
if (hasUnanswered) {
console.log('Some unanswered');
} else {
console.log('All set');
}
e.preventDefault(); // just for demo purposes... normally, just put this in the hasUnanswered part
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
First up, I get all of the radio buttons that have a type of radio (that way if there are others, I won't bother with them).
Then, I turn the NodeList returned by querySelectorAll() into an Array by using Array.prototype.slice.call() and giving it my NodeList.
After that, I use reduce() to group the questions together. I make it an array with the element's name as the key (since I know that's how they have to be grouped). After the reduce, since I don't really care about it being an object with the key, I use Object.values() just to get the arrays.
After that, I use some() over the set of questions. If that returns true, it'll mean I have at least one unanswered question.
Finally, inside that some(), I do another over the individual radio buttons of the question. For this, I want to return !some() because if there isn't at least one that is answered, then I should return true overall (that I have at least one question not answered).
The above is a bit verbose. This one is a bit more concise and is what I would likely use in my own code:
document.querySelector('form').addEventListener('submit', e => {
if (Object.values(
Array.prototype.reduce.call(
document.querySelectorAll('input[type=radio]'),
(result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }),
{}
)
).some(q => !q.some(el => el.checked))) {
e.preventDefault();
console.log('Some questions not answered');
}
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
Everything inside your for clause makes absolutely no sense. Here's why:
Since you already have inputRadios, there is no point and getting their name and then using that to get the elements by name, because you already have them.
Since you use return true, the function exits and everything beyond that is disregarded.
Instead of updating the existent all_answered variable you create a new, local one that will be lost once the current iteration ends.
What you should do:
Instead of getting all inputs, get all answers, the div.options elements that contain the inputs for each answer, and iterate over those.
Then, use the id of the answer, because it's the same as the name of the inputs, to get the related inputs.
Use some to ensure that there is a checked input among the group. Then, check whether there isn't and stop the loop. You've found an unanswered question.
Snippet:
document.getElementById("submit_btn").addEventListener("click", function(event) {
var
/* Create a flag set by default to true. */
all_answered = true,
/* Get all answers. */
answers = document.querySelectorAll(".options[id ^= ans_]");
/* Iterate over every answer. */
for (var i = 0; i < answers.length; i++) {
var
/* Use the id of the answer to get its radiobuttons. */
radios = document.querySelectorAll("[name = " + answers[i].id + "]"),
/* Save whether there is a checked input for the answer. */
hasChecked = [].some.call(radios, function(radio) {
return radio.checked;
});
/* Check whether there is a checked input for the answer or not. */
if (!hasChecked) {
/* Set the all_answered flag to false and break the loop. */
all_answered = false;
break;
}
}
/* Check whether not all answers have been answered. */
if (!all_answered) {
console.log("Some questions were not answered...");
} else {
console.log("All questions are answered!");
}
});
.question { display: inline-block }
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_286">
<div class="radio-button">
<input type="radio" value="3" id="ans34op1" name="ans_286">
<label for="ans34op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans34op2" name="ans_286">
<label for="ans34op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans34op3" name="ans_286" class="custom">
<label for="ans34op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans34op4" name="ans_286">
<label for="ans34op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_287">
<div class="radio-button">
<input type="radio" value="3" id="ans35op1" name="ans_287">
<label for="ans35op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans35op2" name="ans_287">
<label for="ans35op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans35op3" name="ans_287" class="custom">
<label for="ans35op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans35op4" name="ans_287">
<label for="ans35op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<button id="submit_btn">Submit</button>
The following is a simplified version, but there should be enough code to get you heading in the right direction.
var answer = [];
function checkAnswerCount(e) {
// for the answer ids
var i = 0, max = answer.length;
// for the radios
var j = 0; rMax = 0;
// And a few extras
var tmp = null, answerCount = 0;
for(;i<max;i++) {
tmp = document.getElementsByName(answer[i]);
rMax = tmp.length;
for(j=0;j<rMax;j++) {
if (tmp[j].checked) {
answerCount++;
break;
}
}
}
if (answerCount == answer.length) {
console.log("All questions have an answer, submit the form");
} else {
console.log("You need to answer all the questions");
}
}
window.onload = function() {
// each answer block is surrounded by the "options" class,
// so we use that to collect the ids of the raido groups
var a = document.querySelectorAll(".options");
var i = 0, max = a.length;
for(;i<max;i++) {
answer.push(a[i].id);
}
// And we want to check if all the answers have been answered
// when the user tries to submit...
var s = document.getElementById("submitAnswers");
if (s) {
s.addEventListener("click",checkAnswerCount,false);
}
}
<p>Question 1.</p>
<div class="options" id="ans_1">
<label><input type="radio" name="ans_1" value="a1_1" /> Answer 1, op1</label>
<label><input type="radio" name="ans_1" value="a1_2" /> Answer 1, op2</label>
</div>
<p>Question 2.</p>
<div class="options" id="ans_2">
<label><input type="radio" name="ans_2" value="a2_1" /> Answer 2, op1</label>
<label><input type="radio" name="ans_2" value="a2_2" /> Answer 2, op2</label>
</div>
<p>Question 3.</p>
<div class="options" id="ans_3">
<label><input type="radio" name="ans_3" value="a3_1" /> Answer 3, op1</label>
<label><input type="radio" name="ans_3" value="a3_2" /> Answer 3, op2</label>
</div>
<button id="submitAnswers">Submit / check</button>
I am trying to check if the radio button is checked or not, and also I am trying to get the value but I do not know why it does not work. I saw a lot of post, video on internet and also some on this site, but nothing. So helpless I am posting this on the site.
This is my HTML file
function getValue(){
var checkAge = false;
for(var i=0; i<4; i++){
if(document.getElementById("age"+i).checked){
checkAge = true;
}
}
}
function loadFunctions() {
getValue();
}
window.onload = loadFunctions;
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form id="form">
<section id="age_question">
<h2>How old are you?</h2>
<label for="age-one">1-25</label>
<input type="radio" name="ageRange" id="age1" value="0"/>
<label for="age-two">26-40</label>
<input type="radio" name="ageRange" id="age2" value="5" />
<label for="age-three">41-60</label>
<input type="radio" name="ageRange" id="age3" value="8" />
<label for="age-four">60+</label>
<input type="radio" name="ageRange" id="age4" value="10" />
</section>
<section id="bmi">
<h2>What is your BMI?</h2>
<label for="bmi-level"><span>0-25</span></label>
<input type="radio" name="bmi_range" id="" value="0"/>
<label for="bmi-level"><span>26-30</span></label>
<input type="radio" name="bmi_range" id="" value="0" />
<label for="bmi-level"><span>31-35</span></label>
<input type="radio" name="bmi_range" id="" value="9" />
<label for="bmi-level"><span>35+</span></label>
<input type="radio" name="bmi_range" id="" value="10" />
</section>
<section id="family_history">
<h2>Does anybody in your family have Diabetes?</h2>
<label for="history"><span>No</span></label>
<input type="radio" name="f_history" id="history" value="0"/>
<label for="history"><span>Grandparent</span></label>
<input type="radio" name="f_history" id="history" value="7" />
<label for="history"><span>Sibling</span></label>
<input type="radio" name="f_history" id="history" value="15" />
<label for="history"><span>Parent</span></label>
<input type="radio" name="f_history" id="history" value="15" />
</section>
<section id="diet">
<h2>How would you describe your diet?</h2>
<label for="diet"><span>Low sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0"/>
<label for="diet"><span>Normal sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0" />
<label for="diet"><span>Quite high sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="7" />
<label for="diet"><span>High sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="10" />
</section>
<button onclick="getValue()">Get You BMI</button>
<p id="message"></p>
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The first thing I'll suggest you do is to clear your browser cache, or launch the dev tools using F12 and check "Disable cache" on the "Network" tab.
Edit: Changed the button type, and made checkAge global.
Okay, the button does submit the form, making all changes to the variable lost after reload. To fix that, change the button type to just button, as:
<button type="button" onclick="getValue()">Get You BMI</button>
That way, it won't reload everytime you press the button. Another thing to do is make the checkAge variable global. that way is defined as false by default.
The "age"+i thing you did was starting the iteration with i=0, therefore giving the elementId as age0. This was making the element null.
To fix that, you can change the for-loop to for(var i=1; i<=4; i++) or using the same loop you've defined, but adding i by 1 before using it.
And the code would be like so:
var checkAge = false;
function getValue(){
for(var i=0; i<4; i++){
var index = i + 1
var element = document.getElementById("age"+index)
if(element.checked){
checkAge = true;
alert("The value is"+element.value)
}
}
}
Thanks.
Make the starting index be 1 instead of 0, since your ID selectors start from 1:
function getValue() {
var checkAge = false
for (var i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked) {
checkAge = true
}
}
console.log(checkAge)
return checkAge
}
JSFiddle Demo: https://jsfiddle.net/a3fzd2kv/2/
You don't need to check the checked value of each of the radio buttons.
Here is a simpler solution:
var form = document.getElementById('form');
var ageRange = form.ageRange.value;
The value will equal to an empty string ('') when nothing is checked. Therefore, the logic for checkAge could be simplified to:
var checkAge = ageRange !== '';
your for loop is looping through i from 0 - 3, so your document.getElementById("age"+i) will look for id="age0", "age1", "age2, "age3".
Change your 'for' loop to for(var i=1; i<5; i++)
I'm making an online examination website. We have many forms created by for loop in jsp. Each form has 1 multiple choice question and 4 answers.
I wrote a script using jquery to check wheter user makes right or wrong that question.
for (int i = 0; i < NumofQuestions; i++) {
Question q = (Question) exam.get(i); %>
<form>
<p><b>Question <%=i+1%>: </b> <%=q.getContent()%></p>
<p><b>A. </b><input type="radio" name="answer" value="A"><%=q.getAnswerA()%><br></p>
<p><b>B. </b><input type="radio" name="answer" value="B"><%=q.getAnswerB()%><br></p>
<p><b>C. </b><input type="radio" name="answer" value="C"><%=q.getAnswerC()%><br></p>
<p><b>D. </b><input type="radio" name="answer" value="D"><%=q.getAnswerD()%><br></p>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("form").on('click',function() {
$this = $(this);
var value = $this.find('input:radio[name=answer]:checked').val();
var correct = "<%=q.getAnswer()%>";
if (value == correct) {
$('#result').html('right');
} else {
$('#result').html('wrong');
}
});
</script>
<% } %>
Although the script contains in for loop but the variable correct always returns the last element of list exam. Means q.getAnswer() always gets the answer of the last question not the question which is doing. Are there any ways to solve that?
Add the correct answer to the form as a data attribute if you do not care a view-source will show it. Otherwise you need to ajax to the server to get the answer. $("form") will get ALL forms on the page and you are including jQuery for each and every form in your loop
Alternatively have one form with multiple radios where each set has its own name.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#formContainer").on("click","input:radio[name=answer]", function() {
var value = this.value, // always the checked value
$form = $(this).closest("form"),
correct = $form.data("correct");
$form.next().html(value == correct ? 'right' : 'wrong');
$("#score").html($(".result:contains('right')").length);
});
});
</script>
<div id="formContainer">
for (int i = 0; i < NumofQuestions; i++) { Question q=( Question) exam.get(i); %>
<form data-correct="<%=q.getAnswer()%>">
<p><b>Question <%=i+1%>: </b>
<%=q.getContent()%>
</p>
<p><b>A. </b>
<input type="radio" name="answer" value="A">
<%=q.getAnswerA()%>
<br>
</p>
<p><b>B. </b>
<input type="radio" name="answer" value="B">
<%=q.getAnswerB()%>
<br>
</p>
<p><b>C. </b>
<input type="radio" name="answer" value="C">
<%=q.getAnswerC()%>
<br>
</p>
<p><b>D. </b>
<input type="radio" name="answer" value="D">
<%=q.getAnswerD()%>
<br>
</p>
</form>
<span class="result"></span>
<% } %>
</div>
<span id="score"></span>
i created a form with cal() but im not able to make it work with radio input.
It worked with select and option, but now the value isnt taken.
here the code
<script>
function cal()
{
var pl=document.form1.template.value;
var resultat=pl;
document.form1.tresultat.value=resultat;
document.formfin.tresultatfin.value = calfin();
}
</script>
<form name="form1">
<label for="Template">Option 1 : Template</label>
<ul>
<li id="template"><label for="logo+texte">Logo et texte</label>
<input type="radio" id="test" name="template" value="500" onclick="cal()"></li>
<li><label for="base">Base</label>
<input type="radio" id="test" name="template" value="800" onclick="cal()"></li>
<li><label for="perso">Sur-Mesure</label>
<input type="radio" id="test" name="template" value="2900" onclick="cal()"></li></ul>
<input type="text" value="0" name="tresultat">
</form>
any idea to get the value in the text input when selected ?
thanks
Radio buttons are weird because there's a list of separate elements instead of just one. The simplest thing to do is to pass the element itself as a parameter:
function cal( button )
{
var pl = button.value;
var resultat=pl;
document.form1.tresultat.value=resultat;
document.formfin.tresultatfin.value = calfin();
}
and then change the radio buttons:
<input type="radio" id="test" name="template" value="800" onclick="cal( this )"></li>
passing this to the function.