I posted this question yesterday, but deleted as I had to fix my code to make it much more neat. But for my assignment, I have to make a quiz in JavaScript, but I also have to make it so that whenever the user retakes the quiz, the questions and answer choices are shuffled, meaning in a different order. I have seen examples of this on the website before, but they placed their choices and questions in arrays, and I did my quiz without arrays. Is there still a way to do this? Thank you.
This is the JS code (I can not put it in a JSFiddle because it says that the code needs to be pure JS):
function gradeTest() {
//variables with global implications
var totalPoints = 18;
var numberOfPoints = 0;
var numberofQuestions = 0;
var alertText;
var i;
function multipleChoice(idOfQuestion, answer, idOfText) {
var select = document.getElementsByName(idOfQuestion);
for(i = 0; i < select.length; i++) {
if(select[i].checked) {
if(select[i].value == answer) {
numberOfPoints++;
numberofQuestions++;
changeColor(1, idOfText);
break;
}
} else { changeColor(0, idOfText) }
}
}
var a1 = document.getElementById('q1').value.toLowerCase();
if(a1 == '<script>') {
numberOfPoints = numberOfPoints + 2;
numberofQuestions++;
changeColor(1, 's1');
} else { changeColor(0, 's1') }
var a2 = document.getElementById('q2').value.toLowerCase();
if(a2 == '//') {
numberOfPoints = numberOfPoints + 2;
numberofQuestions++;
changeColor(1, 's2');
} else { changeColor(0, 's2') }
multipleChoice('q3','false','b1')
multipleChoice('q4','true','b2')
multipleChoice('q5','false','b3')
multipleChoice('q6','true','b4')
multipleChoice('q7','popup','m1')
multipleChoice('q8','false','m2')
multipleChoice('q9','2','m3')
multipleChoice('q10','10','m4')
multipleChoice('q11','inner','m5')
multipleChoice('q12','11','m6')
multipleChoice('q13','5','m7')
multipleChoice('q14','slash','m8')
multipleChoice('q15','no','m9')
multipleChoice('q16','11','m10')
if(numberOfPoints == totalPoints) {
alertText = "Congratulations! You got all the questions right!";
}
else {
if(numberOfPoints > 5) {
alertText = "You got " + numberOfPoints + " out of " + totalPoints + " possible points! You also got " + numberofQuestions + " right!";
}
else {
alertText = "You got " + numberOfPoints + " out of " + totalPoints + " correct. And that means you got " + numberofQuestions + " right.... Know your javascript more..."; } }
alert(alertText);
}
This is the HTML code:
<form id="test">
<table border="1" cellspacing="0" cellpadding="5" class="table">
<tr>
<td class="set" id = "s1" name="short">Inside which HTML element do we put the JavaScript?</td>
<td>
<input id="q1" maxlength="30" name="q1" size="30" type="text" /></td>
</tr>
<tr>
<td class="set" id = "s2" name="short">What do you use for line comments?</td>
<td>
<input id="q2" maxlength="30" name="q2" size="30" type="text" /></td>
</tr>
<tr>
<td class="set" id = "b1" name="boolean">'document.getElementById' is not a valid Javascript Request.</td>
<td>
<input name="q3" type="radio" value="true" />
True |
<input name="q3" type="radio" value="false" />
False</td>
</tr>
<tr>
<td class="set" id = "b2" name="boolean">Javascript is case-sensitive.</td>
<td>
<input name="q4" type="radio" value="true" />
True |
<input name="q4" type="radio" value="false" />
False</td>
</tr>
<tr>
<td class="set" id = "b3" name="boolean">There is no such Math object in Javascript.</td>
<td>
<input name="q5" type="radio" value="true" />
True |
<input name="q5" type="radio" value="false" />
False</td>
</tr>
<tr>
<td class="set" id = "b4" name="boolean">"1" + 2 + 4 evaluates to "124"</td>
<td>
<input name="q6" type="radio" value="true" />
True |
<input name="q6" type="radio" value="false" />
False</td>
</tr>
<tr> <!-- check -->
<td class="set" id = "m1" name="mult">What does 'alert' do?</td>
<td>
<input name="q7" type="radio" value="popup" />
Creates a popup window based on text. |
<input name="q7" type="radio" value="reminder" />
It sets a reminder. |
<input name="q7" type="radio" value="command" />
It sets an in-built command to alert the user about a certain function being performed. |
<input name="q7" type="radio" value="none" />
None of these</td>
</tr>
<tr>
<td class="set" id = "m2" name="mult">What is the result of '(true + false) > 2 + true;'?</td>
<td>
<input name="q8" type="radio" value="true" />
true |
<input name="q8" type="radio" value="false" />
false |
<input name="q8" type="radio" value="error" />
TypeError |
<input name="q8" type="radio" value="none" />
None of these</td>
</tr>
<tr>
<td class="set" id = "m3" name="mult">What is the result of '"1" - - "1";'?</td>
<td>
<input name="q9" type="radio" value="1" />
1 |
<input name="q9" type="radio" value="2" />
2 |
<input name="q9" type="radio" value="11" />
11 |
<input name="q9" type="radio" value="none" />
None of these</td>
</tr>
<tr>
<td class="set" id = "m4" name="mult">'function() {
var a = 10;
if(a > 5) {
a = 7;
}
alert(a);
}'
What is the value that will be alerted?</td>
<td>
<input name="q10" type="radio" value="7" />
7 |
<input name="q10" type="radio" value="null" />
null |
<input name="q10" type="radio" value="10" />
10 |
<input name="q10" type="radio" value="undefined" />
undefined</td>
</tr>
<tr>
<td class="set" id = "m5" name="mult">What do you use to change HTML?</td>
<td>
<input name="q11" type="radio" value="inner" />
.innerHTML |
<input name="q11" type="radio" value="change" />
.changeHTML |
<input name="q11" type="radio" value="html" />
.HTML |
<input name="q11" type="radio" value="doc" />
.documentChangeHTML</td>
</tr>
<tr>
<td class="set" id = "m6" name="mult">var price1 = 5;<br>
var price2 = 6;<br>
var total = price1 + price2;</td>
<td>
<input name="q12" type="radio" value="11" />
total = 11 |
<input name="q12" type="radio" value="56" />
total = 56 |
<input name="q12" type="radio" value="colon" />
total = 5;6; |
<input name="q12" type="radio" value="none" />
None of The Above</td>
</tr>
<tr>
<td class="set" id = "m7" name="mult">var x = "'ABC'"</td>
<td>
<input name="q13" type="radio" value="3" />
x.length = 3 |
<input name="q13" type="radio" value="5" />
x.length = 5 |
<input name="q13" type="radio" value="22" />
x.length = 22 |
<input name="q13" type="radio" value="none" />
None of The Above</td>
</tr>
<tr>
<td class="set" id = "m8" name="mult">How do you insert special characters into a string in JS?</td>
<td>
<input name="q14" type="radio" value="//" />
// |
<input name="q14" type="radio" value="slash" />
\ |
<input name="q14" type="radio" value="&" />
& |
<input name="q13" type="radio" value="nope" />
You can't.</td>
</tr>
<tr>
<td class="set" id = "m9" name="mult">Can objects be compared?</td>
<td>
<input name="q15" type="radio" value="no" />
No |
<input name="q15" type="radio" value="yes" />
Yes |
<input name="q15" type="radio" value="certain" />
On certain circumstances. |
<input name="q15" type="radio" value="lol" />
Objects don't exist.</td>
</tr>
<tr>
<td class="set" id = "m10" name="mult">What does 'document.write(5 + 6)' place in the HTML page?</td>
<td>
<input name="q16" type="radio" value="11" />
11 |
<input name="q16" type="radio" value="duo" />
5+6 |
<input name="q16" type="radio" value="56" />
56 |
<input name="q16" type="radio" value="error" />
TypeError</td>
</tr>
</table>
<br>
<input onclick="gradeTest()" name="submit" type="button" value="Grade This Test" />
Thank you very much.
EDIT: There was a line of code that needed to be removed. It had no purpose.
EDIT: More code removed.
Here is a JavaScript solution to shuffle the elements inside a parent element for shuffling elements by tag name like tr.
function getRandom(max) {
return Math.floor(Math.random()*max);
}
function shuffleElements(parentElement, tag) {
var tagsObj = document.getElementsByTagName(tag);
var tags = Array();
//getElementsByTagName gives you an Object, so converting that to Array().
for(var i=0;i<Object.keys(tagsObj).length;i++) {
tags.push(tagsObj[i]);
}
var length = tags.length;
var randomized = Array();
//Randomize the elements of the tags array.
for(var i=0; i<length; i++) {
var random = getRandom(tags.length);
randEl = tags[random];
tags.splice(random,1);
randomized.push(randEl);
}
//Put the randomized elements in the Parent.
document.getElementsByTagName(parentElement)[0].innerHTML = '';
var final = '';
for(var i=0; i<randomized.length; i++) {
final += (randomized[i].outerHTML);
}
document.getElementsByTagName(parentElement)[0].innerHTML = final;
}
So you can use the above function to randomize the elements inside your table like below-
shuffleElements('table','tr');
Here is a working Fiddle with your code - https://jsfiddle.net/jpfdsbhx/1/
PS - I changed the answer in your code from <script> to script to make it run with JSFiddle.
Related
I am trying to show/hide a div based on the selection made using a radio button in HTML.
HTML Code:
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cheque
<div id="chequeContainer" class = "chequeContainer" style="display:none;">
<tr>
<td>Bank Name:</td><td><input type = "text" name = "bank"></td>
<td>Branch:</td><td><input type = "text" name = "branch"></td>
<td>Cheque No:</td><td><input type = "text" name = "chequeno"></td>
</div>
Javascript Code:
function displayForm(c) {
alert(c.value);
if (c.value == "cheque") {
document.getElementById("chequeContainer").style.display = 'inline';
}
else if (c.value == "cash") {
document.getElementById("chequeContainer").style.display = 'none';
}
else {}
}
Hi you made a typo mistake in the element value. Instead of providing different value to the input field, values, you gave value="cheque" for both radio buttons. I hope this will help you.
function displayForm(c) {
if (c.value == 'cheque') {
document.getElementById("chequeContainer").style.display = 'inline';
}
else {
document.getElementById("chequeContainer").style.display = 'none';
}
}
<input value="cash" type="radio" name="selector" onClick="displayForm(this)"></input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cheque
<div id="chequeContainer" class = "chequeContainer" style="display:none;">
<tr>
<td>Bank Name:</td><td><input type = "text" name = "bank"></td>
<td>Branch:</td><td><input type = "text" name = "branch"></td>
<td>Cheque No:</td><td><input type = "text" name = "chequeno"></td>
</div>
Two input tag with same value :
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cheque
Change the as following :
<input value="cash" type="radio" name="selector" onClick="displayForm(this)"></input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)"></input>Cheque
IT SHOULD WORK FINE
Full Code :
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input value="cash" type="radio" name="selector" onClick="displayForm(this)">
</input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(this)">
</input>Cheque
<div id="chequeContainer" class = "chequeContainer" style="display:none;">
<tr>
<td>Bank Name:
</td>
<td>
<input type = "text" name = "bank">
</td>
<td>Branch:
</td>
<td>
<input type = "text" name = "branch">
</td>
<td>Cheque No:
</td>
<td>
<input type = "text" name = "chequeno">
</td>
</div>
<script>
function displayForm(c) {
if (c.value == "cheque") {
document.getElementById("chequeContainer").style.display = 'inline';
}
else if (c.value == "cash") {
document.getElementById("chequeContainer").style.display = 'none';
}
else {}
}
</script>
</body>
</html>
$(document).ready(function () {
$('input:radio[name="selector"]').change(function () {
if ($(this).val() == 'cheque') {
document.getElementById("chequeContainer").style.display = 'inline';
}
else if ($(this).val() == "cash") {
document.getElementById("chequeContainer").style.display = 'none';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" name="selector" value="cheque" /> Cheque<br>
<input value="cash" type="radio" name="selector" />Cash<br><br>
<div id="chequeContainer" class="chequeContainer" style="display: none;">
<table>
<tr>
<td>
Bank Name:
</td>
<td>
<input type="text" name="bank">
</td>
<td>
Branch:
</td>
<td>
<input type="text" name="branch">
</td>
<td>
Cheque No:
</td>
<td>
<input type="text" name="chequeno">
</td>
</tr>
</table>
</div>
</div>
You could even do this without using javascript.
#cheque:not(:checked)~#chequeContainer {
display: none;
}
#cheque:checked~#chequeContainer {
display: inline;
}
<input id="cash" value="cash" type="radio" name="selector">
<label for="cash">Cash</label>
<input id="cheque" value="cheque" type="radio" name="selector">
<label for="cheque">Cheque</label>
<div id="chequeContainer" class="chequeContainer">
<tr>
<td>Bank Name:</td>
<td><input type="text" name="bank"></td>
<td>Branch:</td>
<td><input type="text" name="branch"></td>
<td>Cheque No:</td>
<td><input type="text" name="chequeno"></td>
</tr>
</div>
Tyr this
<input value="cheque" type="radio" name="selector" onClick="displayForm(this.value)"/>Cash
<input value="cash" type="radio" name="selector" onClick="displayForm(this.value)"/>Cheque
<div id="chequeContainer" class="chequeContainer" style="display:none;">
<tr>
<td>Bank Name:</td>
<td><input type="text" name="bank"></td>
<td>Branch:</td>
<td><input type="text" name="branch"></td>
<td>Cheque No:</td>
<td><input type="text" name="chequeno"></td>
</tr>
</div>
javascript:
function displayForm(val) {
alert(val);
if (val == "cheque") {
document.getElementById("chequeContainer").style.display = 'inline';
}
else if (val == "cash") {
document.getElementById("chequeContainer").style.display = 'none';
}
else { }
}
<input value="cash" type="radio" name="selector" onClick="displayForm(1)"></input>Cash
<input value="cheque" type="radio" name="selector" onClick="displayForm(2)"></input>Cheque
function displayForm(val) {
if (val == "2" || val == 2) {
document.getElementById("chequeContainer").style.display = 'inline';
}
else {
document.getElementById("chequeContainer").style.display = 'none';
}
}
I am working on a new security assessment webpage in which I am using HTML and Java Script. For some reason, the code is not working properly. The way the page supposed to work is by having the user answer Yes or No questions, and when the user is done they click submit. Then the page would display the number of questions answered yes, and a message if the user passed or failed the assessment. But when I click submit, I only see the result, not the message.
Any feedback would be appreciated.
function sumInputs() {
var text;
var score = document.getElementById("total").value;
if (score < 60) {
text = "You have failed the Assessment";
} else(score > 60) {
text = "You have passed the Assessment";
}
document.getElementById("demo").innerHTML = text;
}
function calcscore() {
var score = 0;
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});
window.sumInputs = function() {
var inputs = $('.calc:checked'),
result = document.getElementById('total'),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
sum += parseInt(inputs[i].value);
}
$('#total').val(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p id="demo"></p>
<h1>Security Assessment </h1>
<table>
<tr>
<th>PERSONNEL SECURITY</th>
</tr>
<tr>
<td>1. Does your staff wear ID badges?
<form>
Yes
<input class="calc" type="radio" name="radio1" value="1" /> No
<input class="calc" type="radio" name="radio1" value="0" /><br />
</td>
</tr>
<tr>
<td>2. Is a current picture part of the ID badge? Yes
<input class="calc" type="radio" name="radio2" value="1" /> No
<input class="calc" type="radio" name="radio2" value="0" /><br />
</td>
</tr>
<tr>
<td>3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge? Yes
<input class="calc" type="radio" name="radio3" value="1" /> No
<input class="calc" type="radio" name="radio3" value="0" /><br />
</form>
</td>
</tr>
</table>
Total : <input type="text" name="total" id="total" />
<input type="Submit" value="Submit" onclick="sumInputs()">
</body>
</html>
Check if this works. Also check your variable type
function calcscore() {
var score = 0;
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});
function sumInputs() {
var inputs = $('.calc:checked'),
result = document.getElementById('total'),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
sum += parseInt(inputs[i].value);
}
$('#total').val(sum);
var text, score = document.getElementById("total").value;
if (score < 60) {
text = "You have failed the Assessment";
} else if(score > 60) {
text = "You have passed the Assessment";
}
document.getElementById("demo").innerHTML = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<h1>Security Assessment </h1>
<table>
<tr>
<th>PERSONNEL SECURITY</th>
</tr>
<tr>
<td>1. Does your staff wear ID badges?
<form>
Yes
<input class="calc" type="radio" name="radio1" value="1" />
No
<input class="calc" type="radio" name="radio1" value="0" /><br />
</form>
</td>
</tr>
<tr>
<td>2. Is a current picture part of the ID badge?
<form>
Yes
<input class="calc" type="radio" name="radio2" value="1" />
No
<input class="calc" type="radio" name="radio2" value="0" /><br />
</form>
</td>
</tr>
<tr>
<td>3. Are authorized access levels and type (employee, contractor, visitor) identified
on the Badge?
<form>
Yes
<input class="calc" type="radio" name="radio3" value="1" />
No
<input class="calc" type="radio" name="radio3" value="0" /><br />
</form>
</td>
</tr>
</table>
Total : <input type="text" name="total" id="total"/>
<input type="Submit" value="Submit" onclick="sumInputs()">
<p id="demo"></p>
</body>
</html>
You have two functions named sumInputs; the second one (which filled the 'score' field) was overwriting the first one (which was supposed to output the message.)
Additionally the scoring was trying to be based on percentages, but never calculated a percentage, just a count of correct questions.
(There were also a couple of syntax errors here and there.)
Correcting all those by merging the two sumInputs functions results in:
function calcscore() {
var score = 0;
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});
window.sumInputs = function() {
var inputs = $('.calc:checked'),
result = document.getElementById('total'),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
sum += parseInt(inputs[i].value);
}
$('#total').val(sum);
var score = sum / 3 * 100; // calculate percentage
if (score < 60) {
text = "You have failed the Assessment";
} else { // no need for else if (score > 60)... which would have failed if the score was exactly 60
text = "You have passed the Assessment";
}
document.getElementById("demo").innerHTML = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p id="demo"></p>
<h1>Security Assessment </h1>
<table>
<tr>
<th>PERSONNEL SECURITY</th>
</tr>
<tr>
<td>1. Does your staff wear ID badges?
<form>
Yes
<input class="calc" type="radio" name="radio1" value="1" /> No
<input class="calc" type="radio" name="radio1" value="0" /><br />
</td>
</tr>
<tr>
<td>2. Is a current picture part of the ID badge? Yes
<input class="calc" type="radio" name="radio2" value="1" /> No
<input class="calc" type="radio" name="radio2" value="0" /><br />
</td>
</tr>
<tr>
<td>3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge? Yes
<input class="calc" type="radio" name="radio3" value="1" /> No
<input class="calc" type="radio" name="radio3" value="0" /><br />
</form>
</td>
</tr>
</table>
Total : <input type="text" name="total" id="total" />
<input type="Submit" value="Submit" onclick="sumInputs()">
</body>
</html>
Incidentally, the calcscore() function is unnecessary -- it updates the displayed score while the user takes the quiz, but the sumInputs function used at the end of the quiz doesn't depend on it. If you don't want to give the user immediate feedback on whether each question was correct or not, you can remove that function (and move $("input[name=sum]").val(score) into sumInputs().
I added some already done modifications, and changed the plain javascript to jquery.
$('.calc').change(function() {
calcscore();
});
$('#submitted').click(function() {
sumInputs();
result();
});
function sumInputs() {
var inputs = $('.calc:checked'),
result = $('#total').val(),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
sum += parseInt(inputs[i].value);
}
$('#total').val(sum);
}
function result() {
var text;
var score = (( $('#total').val() ) / 3 ) * 100;
var score = score.toFixed(2);
if (score < 60) {
text = "Total " + score + ": You have failed the Assessment";
}
else {
text = "Total " + score + ": You have passed the Assessment";
}
$('#demo').text(text);
}
function calcscore() {
var score = 0;
$('.calc:checked').each(function () {
score += parseInt($(this).val(), 10);
});
$('#total').val(score);
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1>Security Assessment </h1>
<form>
<table>
<tr>
<th>PERSONNEL SECURITY</th>
</tr>
<tr>
<td>1. Does your staff wear ID badges?
Yes <input class="calc" type="radio" name="radio1" value="1" />
No <input class="calc" type="radio" name="radio1" value="0" /><br />
</td>
</tr>
<tr>
<td>2. Is a current picture part of the ID badge?
Yes <input class="calc" type="radio" name="radio2" value="1" />
No <input class="calc" type="radio" name="radio2" value="0" /><br />
</td>
</tr>
<tr>
<td>3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge?
Yes <input class="calc" type="radio" name="radio3" value="1" />
No <input class="calc" type="radio" name="radio3" value="0" /><br />
</td>
</tr>
</table>
</form>
Total : <input type="text" name="total" id="total" />
<input id="submitted" type="Submit" value="Submit"><br><br>
<p id="demo"></p>
</body>
</html>
I need a page I am creating to take the submitted info and then display it on the page when submit is pressed. The way I have it now it prints the name, email, years of experience, date, references and additional comments. Compensation and Region selected print as undefined...
Please help!!
<script type="text/javascript">
info = document.getElementById("personalInfo");
info.innerHTML = "<strong>Peronal Info: </strong>" + "<br>" + "Name: " +
document.feedback.fname.value +
" " +
document.feedback.lname.value +
"<br>" + "Email: " +
document.feedback.email.value;
info = document.getElementById("experienceSubmit");
var compensationValue,regionValue;
//Get compensation value
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
compensationValue = document.feedback.comp[i].value;
}
}
//Get region value
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
regionValue = document.feedback.region[i].value;
}
}
info = document.getElementById("otherSubmit");
info.innerHTML = "<strong>Other information: </strong>" + "<br>" + "# of References " +
document.feedback.reference.value +
"<br>" + "Additional Comments: " +
document.feedback.comments.value;
return false;
}
</script>
</head>
<body background="../Assignment 5/_images/abstract_color_background_picture_8016-wide.jpg" >
<form name="feedback" method="post" onSubmit="return checkform()">
<section id="pinfo" class="inputArea">
<fieldset>
<table>
<tr>
<td>Last Name: </td>
<td><input name="lname"
type="text"
autofocus
required
placeholder="lname"
size="25" />
</td>
</tr>
<tr>
<td>First Name: </td>
<td><input name="fname"
type="text"
size="25"
required
placeholder="fname" />
</td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email"
type="email"
size="40"
required
placeholder="....#hotmail.com" />
</td>
</tr>
<td>Gender: </td>
<td><select name="gender">
<option selected disabled style='display:none;'>
Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
</tr>
</table>
</fieldset>
</section>
<section id="experience">
<fieldset>
<table>
<tr>
<td>
<label for="experience">Years of Experience: </label>
<input name="experience" type="number" />
</td>
</tr>
<tr>
<td>
<label for="date">Date</label>
<input name="date" type="date" />
</td>
<tr>
<td>
<label for="comp">Compensation: </label><br>
<input name="comp" type="radio" id="Salary" value="Salary Selected">Salary
<input name="comp" type="radio" id="SalaryWB" value="Salary with bonus Selected">Salary with Bonus
<input name="comp" type="radio" id="Commission" value="Commission Selected">Commission
</td>
</tr>
<tr>
<td>
<label for="region">Region: </label><br>
<input name="region" type="checkbox" id="East" value="East Selected">East
<input name="region" type="checkbox" id="West" value="West Selected">West
<input name="region" type="checkbox" id="North" value="North Selected">North
<input name="region" type="checkbox" id="South" value="South Selected">South
</td>
</tr>
</table>
</fieldset>
</section>
<section id="other">
<fieldset>
<table>
<tr>
<td>
<label for="reference">References<br>0   1   2    3    4    5<br></label>
<input name="reference" id="reference"
type="range"
value="0"
min="0"
max="5"
step="1" />
</td>
</tr>
<tr>
<td>
<label for="comments">Additional Comments: <br></label>
<textarea
name="comments"
rows="5"
cols="20"
placeholder="Please include any other pertinent information here"></textarea> </td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</section>
</form>
<section id="personalInfo"></section>
<section id="experienceSubmit"></section>
<section id="otherSubmit"></section>
</body>
The way you are using to get the value of the checkboxes and radio buttons is wrong. You can use this piece of code to get the checked value of the radio buttons or checkboxes.
Radio Buttons
var radios = document.getElementsByName('comp');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Checkboxes
var checkedValues = [];
var inputElements = document.getElementsByName('region');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValues.push(inputElements[i].value);
}
}
var str = checkedValues.ToString(); // all the selected regions in a string.
You could loop through the collection and check whether it is checked or not.
This code if for your compensation:
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
alert(document.feedback.comp[i].value)
}
}
This code is for your region:
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
alert(document.feedback.region[i].value)
}
}
Here is it in your code[ Added on request of user ]:
info = document.getElementById("experienceSubmit");
var compensationValue,regionValue;
//Get compensation value
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
compensationValue = document.feedback.comp[i].value;
}
}
//Get region value
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
regionValue = document.feedback.region[i].value;
}
}
info.innerHTML = "<strong>Experience and Salary: </strong>" + "<br>" + "Years of experience: " +
document.feedback.experience.value +
"<br>" + "Date of availability: " +
document.feedback.date.value +
"<br>" + "Compensation Chosen: " +
compensationValue +
"<br>" + "Region Selected: " +
regionValue;
<tr>
<td><b>If the registration is for either a Consultant or End User Business</b></td>
<td> </td> <td>Please tick box (multiple choice) their area of business</td></tr Question being asked
<td align="right"><b>Consultant or End User: </b>
<td><font color="red">*</font></td>
<td><input type="checkbox" name="Data" value="Yes">Data Centres
<br />
<input type="checkbox" name="Power" value="Yes">Power Plants
<br />
<input type="checkbox" name="Mining" value="Yes">Mining
<br />
<input type="checkbox" name="Telecom" value="Yes">Telecom
<br />
<input type="checkbox" name="Governmental" value="Yes">Governmental
<br />
<input type="checkbox" name="Airports" value="Yes">Airports
<br />
<input type="checkbox" name="Hotel" value="Yes">Hotel/Residential
<br />
<input type="checkbox" name="Healthcare" value="Yes">Healthcare
<br />
<input type="checkbox" name="Shopping" value="Yes">Shopping Complex
<br />
<input type="checkbox" name="Industries" value="Yes">Industries / Manufacturing
<br />
<input type="checkbox" name="Transport" value="Yes">Transport
<br />
<input type="checkbox" name="Utilities" value="Yes">Utilities
<br />
<input type="checkbox" name="Water" value="Yes">Water Treatment
<br />
<input type="checkbox" name="Construction" value="Yes">Construction
<br />
<input type="checkbox" name="Other" value="Yes">Other
<br />
</td> </tr> <tr> <td colspan="3" align="center" bgcolor="#dadada"> </tr>
<tr>
checkboxes to be ticked if answer provided
UPDATE : Here is the code for textfield
<tr>
<td align="right"><strong>Consulting Company Name: </strong><font color="red">*</font></td>
<td><input size="30" name="ConCompany" class="required"/></td>
</tr>
in first step I would add an id to your textfield, that you can add an eventhandler via JavaScript.
<td><input id="company" size="30" name="ConCompany" class="required"/></td>
Add Eventhandler:
document.getElementById('company').addEventListener('change', setCheckboxesRequired);
Create function to set all checkboxes required:
function setCheckboxesRequired() {
var allInputs, allCheckboxes, textValue, bSetRequired, tmpInput, tmpCheckbox;
// Retrieve all input elements
allInputs = document.getElementsByTagName('input');
allCheckboxes = [];
// put all inputs with type = checkbox in allCheckboxes variable
for (var i = 0; i < allInputs.length; i++) {
tmpInput = allInputs[i];
if (tmpInput.type === 'checkbox') {
allCheckboxes.push(tmpInput);
}
}
// determine if class should be set
textValue = document.getElementById('company').value;
if (textValue === null || textValue === "") {
bSetRequired = false;
} else {
bSetRequired = true;
}
// iteration through all checkboxes
for (var j = 0; j < allCheckboxes.length; j++) {
tmpCheckbox = allCheckboxes[j];
// set or delete class
if (bSetRequired) {
tmpCheckbox.className = tmpCheckbox.className + ' required';
} else {
tmpCheckbox.className = tmpCheckbox.className.replace('required', '');
}
}
}
Or if you want to set HTML5 required-attribute instead of your 'required'-class change the last for-loop to the following:
for (var j = 0; j < allCheckboxes.length; j++) {
tmpCheckbox = allCheckboxes[j];
tmpCheckbox.required = bSetRequired;
}
use a button with some id like submitbtn button like
<input type="button" id="submitbtn" value="Submit" />
Add id to your textbox like id=ConCompany
dd ids to your checkboxes like this:
<input type="checkbox" name="Data" id="10" value="Yes">Data Centres
<br />
<input type="checkbox" name="Power" id="11" value="Yes">Power Plants
<br />
<input type="checkbox" name="Mining" id="12" value="Yes">Mining
<br />
<input type="checkbox" name="Telecom" id="13" value="Yes">Telecom
<br />
<input type="checkbox" name="Governmental" id="14" value="Yes">Governmental
<br />
<input type="checkbox" name="Airports" id="15" value="Yes">Airports
<br />
<input type="checkbox" name="Hotel" id="16" value="Yes">Hotel/Residential
<br />
<input type="checkbox" name="Healthcare" id="17" value="Yes">Healthcare
<br />
<input type="checkbox" name="Shopping" id="18" value="Yes">Shopping Complex
<br />
<input type="checkbox" name="Industries" id="19" value="Yes">Industries / Manufacturing
<br />
<input type="checkbox" name="Transport" id="20" value="Yes">Transport
<br />
<input type="checkbox" name="Utilities" id="21" value="Yes">Utilities
<br />
<input type="checkbox" name="Water" id="22" value="Yes">Water Treatment
<br />
<input type="checkbox" name="Construction" id="23" value="Yes">Construction
Now use the following javascript :
document.getElementById('submitbtn').onclick = function () {
if(document.getElementById('ConCompany').value != "")
{
var count = 0;
for ( var i = 10 ; i <= 23 ; i++)
{
if(document.getElementById(i).value == "Yes")
count++;
}
if(count == 0)
{
alert("Please select the area of business ");
return;
}
}
document.FormName.submit();
}
I am currently working with displaying images based on the value chosen from a radio button. But I am currently running into a wall with making the code as short and efficient as possible. I have several categories to choose from and they way i am approaching the issue will require for me to write several check_value#. Is there a way to combine those two functions? so in the future if i have 5 or 7 categories i wont have to have a function for each. EXAMPLE
<script>
function check_value(val) {
var el = document.getElementById("imgBox1");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/bike" + val + ".jpg";
el.style.display = "";
}
}
function check_value1(val) {
var el = document.getElementById("imgBox2");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/tire" + val + ".jpg";
el.style.display = "";
}
}
</script>
HTML
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2)'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire">
<input type="radio" name="field" value="1" onclick='check_value1(0)'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value1(1)'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value1(2)'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">
try this, updated
make image name as bike#.jpg , tire#.jpg
bike0.jpg, bike1.jpg, bike2.jpg....
function check_value(val, id, type) {
var el = document.getElementById("imgBox" + id);
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/"+ type + val + ".jpg";
el.style.display = "";
}
}
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0, 1, "bike")'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1, 1, "bike")'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2, 1, "bike")'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire">
<input type="radio" name="field" value="1" onclick='check_value(0, 2, "tire")'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value(1, 2, "tire")'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value(2, 2, "tire")'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">
Here is a fiddle for you, using custom HTML attributes, and the jQuery Javascript library:
Obviously you'd want to actually set the image's source, rather than displaying the url in a paragraph, but you get the idea, I'm sure.
// html
<input type="radio" name="tire" img-preview="tire-preview" img-loc="tire/1.jpg" /> First<br>
<input type="radio" name="tire" img-preview="tire-preview" img-loc="tire/2.jpg" /> Second<br>
<p id="tire-preview">
Load: -
</p>
<input type="radio" name="wheel" img-preview="wheel-preview" img-loc="wheel/1.jpg" /> Uno<br>
<input type="radio" name="wheel" img-preview="wheel-preview" img-loc="wheel/2.jpg" /> Dos<br>
<p id="wheel-preview">
Load: -
</p>
// js
$("input[type=radio]").click(function(){
var imageUri = "http://site.com/images/" + $(this).attr("img-loc");
$("#" + $(this).attr("img-preview") ).text("Load: " + imageUri);
});
You can use this
<script>
function call(formNo,val)
{if()//give your checkings here according to what you want
{}
alert(formNo+" "+val); //just for example what values you are getting
}
</script>
<h2>Choose a bike</h2>
<form name="builder" id="1">
<input type="radio" name="field" value="1" onclick='check_value(1,0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1,1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(1,2)'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire" id="2">
<input type="radio" name="field" value="1" onclick='check_value1(2,0)'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value1(2,1)'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value1(2,2)'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">