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>
Related
I need help to validate a form on submit. It should check that one of more checkboxes are selected or else display error message. I have currently got it working but the problem is the checkbox option is displayed after selecting a radio button on the form.
The code I have now still shows an error message even if the div isn't displayed which is a big issue as users haven't seen the checkbox option.
I want the checkbox error message to show ONLY if the user has selected the radio button "NO" and therefor is required to check a checkbox. If they select the radio button "YES" and this checkbox div is not displayed, then I don't want the error message on submit.
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
function validateForm() {
var checked = false;
var elements = document.getElementsByName("tick");
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
if (!checked) {
alert('You must select why you are attending!');
}
return checked;
}
<form id="form" method="post" enctype="text/plain" name="vform">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" name="submit" onclick="validateForm()" value="send">Submit</button>
</div>
</form>
try (select "No" below)
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
// DISPLAY HIDDEN TEXT
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
<form id="form" method="post" enctype="text/plain" name="form">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" onclick="validateForm(event)" name="submit" value="send">Submit</button>
</div>
</form>
Here's the old school way. Just check the display attribute of the div, and only set your flag to false inside that.
function validateForm() {
var checked;
if(document.getElementById("hidden").style.display == "block") {
checked = false;
var elements = document.getElementsByName("tick");
for (var i=0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
}
if (checked===false) {
alert('You must select why you are attending!');
}
return checked;
}
I have three radio buttons groups i want to hide the last two radio button groups which will be displayed once appropriate output from first is given.
The code:
<div class="row">
<div>
<script type="text/javascript">
function displaytxt(e) {
var valueRadio = e;
if (valueRadio == 0)
{
document.getElementById('dynamictxt').style.display = 'none';
}
else
{
document.getElementById('dynamictxt').style.display = '';
}
}
</script>
<div>
<script type="text/javascript">
function displaytxt1(e) {
var valueRadio = e;
if (valueRadio == 2) {
document.getElementById("dynamictxt1").innerHTML = "Check if the termination is for past date or future date";
}
else
{
document.getElementById("dynamictxt1").innerHTML = "Go back to the request manager for confirming the user termination date";
}
}
</script>
Is there a way to do so using java script?
Thanks in advance.
try like this
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
I wish I could understand your question, but based on the title of your question, perhaps, this could help
<form name="form1" method="post" action="">
<p id="rad1"><input type="radio" name="rdbutton" value="radio" id="rdbutton_0">
Radio 1</p>
<p id="rad2"><input type="radio" name="rdbutton" value="radio" id="rdbutton_1">
Radio 2</p>
<p id="rad3"><input type="radio" name="rdbutton" value="radio" id="rdbutton_2">
Radio 3</p>
</form>
<script>
$('#rad1').on('click',function(){
hideSelects();
});
function hideSelects() {
$('p#rad2').hide();
$('p#rad3').hide();
};
</script>
Demo
I have to do a simple work.
I have:
echo' <div class="col-sm-12" id="recensioni_titolo">
<form role="form" id="review-form" method="post" action="php\insert_comment.php">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<input type="text" class="form-control" name="Titolo" id="titolo_review" placeholder="Titolo">
<input type="text" class="form-control" name="ID_locale" id="titolo_review" value="'.$id_Local.'" style="visibility: hidden; position:fixed;">
</div>
</div>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star5'.$id_Local.'" name="Voto" value="5" /><label class = "full" for="star5'.$id_Local.'" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star4'.$id_Local.'" name="Voto" value="4" /><label class = "full" for="star4'.$id_Local.'" title="Buono - 4 stelle"></label>
<input type="radio" id="star3'.$id_Local.'" name="Voto" value="3" /><label class = "full" for="star3'.$id_Local.'" title="Discreto - 3 stelle"></label>
<input type="radio" id="star2'.$id_Local.'" name="Voto" value="2" /><label class = "full" for="star2'.$id_Local.'" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star1'.$id_Local.'" name="Voto" value="1" /><label class = "full" for="star1'.$id_Local.'" title="Pessimo - 1 stella"></label>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control textarea" rows="3" name="Review" id="review" placeholder="Inserisci una descrizione.."></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn main-btn pull-right" name="submit_review" id="submit_review'.$id_Local.'">Invia</button>
</div>
</div>
This code is generating the same thing for 5 times. I'have to find one method to declare and use the id="review-form" in a unique mode because with this code:
$(document.getElementsByName("submit_review")).unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
$.ajax({
url : "php/insert_comment.php",
type : "post",
data : $("#review-form").serialize(),
success : function(data){
$.ajax({
url : "php/reviews.php",
type : "post",
data: {'id_Local' : $('.modal').attr('data-modal')},
success : function(data){
$('#box_recensioni').html(data);
chx[i].checked=false;
}
})
}
})
return true;
}
}
// End of the loop, return false
alert("Inserisci almeno il voto!!")
return false;
});
I have only the first element is working.
I can generate the id with "id'.$variable'" but I don't know how to refers to every single id in the javascript file.
Thank you to all in advance
In HTML, an ID is supposed to be unique :
The id global attribute defines a unique identifier (ID) which must be unique in the whole document.
This is why JavaScript can grab only the first occurence of an ID, since it's supposed to be the only one. You may want to replace those multiple IDs with classes, which is at least correct in HTML5 and will be also smarter in Javascript.
Here is a link to the post in the Mozilla documentation of IDs in HTML, to be sure that you understand the role of this tag.
As other's have said using the same ID would be useless instead you may want to use a class identifier. And assuming you want to create multiple form elements... and you don't have a unique identifier to use in your scripts you may try the following which I haven't tested...
I see you have already gotten the radio button
var chx = document.getElementsByName("Voto");
and performed a check on it under your if statement
if (chx[i].type == 'radio' && chx[i].checked) {
if so, maybe you can try to get the closest form element of the radio button that you are dealing with (i.e. checked) by doing something like
var thisForm = chx[i].closest('form')
--and later do thisForm.serialize();
check this out for more detail in using closest
You can create an array, then use an loop through each radio button pushing the id into the array. Then use the array for the ids.
var radioIds = new Array();
$('.rating input[name="Voto"]').each(function(){
radioIds.push($(this).attr('id'));
});
console.log(radioIds)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star54" name="Voto" value="5" /><label class="full" for="star54" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star44'" name="Voto" value="4" /><label class="full" for="star44" title="Buono - 4 stelle"></label>
<input type="radio" id="star34" name="Voto" value="3" /><label class="full" for="star34" title="Discreto - 3 stelle"></label>
<input type="radio" id="star24'" name="Voto" value="2" /><label class="full" for="star24" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star14" name="Voto" value="1" /><label class="full" for="star14" title="Pessimo - 1 stella"></label>
</fieldset>
</div>
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.
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.