Getting multiple data attributes from checkboxs - javascript

I have a quiz I am making.
Some questions have multiple answers.
My html is as:
<div>Which problems equal 4?</div>
<input type="checkbox" id="qid" class="checks" data-correct="yes">2 + 2<br />
<input type="checkbox" id="qid" class="checks" data-correct="no">2 - 2<br />
<input type="checkbox" id="qid" class="checks" data-correct="yes">2 * 2<br />
I would like to alert if checked answers are both wrong or right.
Currently, my Javascript looks like this:
function checkMsResults(){
var result = $('input[name="qid"]:checked').attr("data-correct");
if(result == '1'){
result = "Answer is Correct";
}
else if(result == '0'){
result = "Answer is Not Correct";
}
else{
result = "Please make a selection";
}
alert(result + ".");
}
This will alert only one selection.
Can someone teach me how to loop through each on so I can alert multiple selections?

You have three inputs with the same id, you can't do that, id must be unique.
function checkMsResults() {
if ($('input[name="quid"]:checked').length === 0) {
var result = "Please make a selection";
alert(result);
return;
}
$('input[name="quid"]:checked').each(function() {
var result;
if (this.getAttribute("data-correct") === "yes") {
result = "Answer is Correct";
} else {
result = "Answer is Not Correct"
}
alert(result);
});
}

Cleaned up your original. Here's a jsfiddle that takes the answer of each and sticks all into an array off answers; you can do whatever you want with it after that...https://jsfiddle.net/r2xc22Ld/1/
function checkMsResults(){
var result = "";
var answers = [];
$('input[name="qid"]:checked').each(function() {
answers.push($(this).attr('data-correct'));
});
//console.log(answers);
for(var i = 0; i< answers.length; i++){
result += 'Question '+i+': ' + answers[i] +'\n';
}
if(result==""){
alert('make a selection...');
}else{
alert(result);
}

Related

I need to increase value of my variabele x if the input is checked , then alert total x

I'm building up a quiz app in javascript only, I want to make the final step which calculates the final score. I have 2 var : myl & score : myl = DOM.checked of my input, score = 0.
I need to make it this way:
if(myl.checked == True) {
score += 1
}
Then I'd like to print the total score in the div, but every time I try to get the total score I get only = 1 and the value of score didn't increased. Can any one help me please
I tried to set score = 0 and myl = DOM.checked and put
if(dom.checked == true) { score += 1} then DOM.innerHTML = score
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var myscore = 0;
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
I always get 1 as result of score, not the total of correct or chosen inputs which should be 4
Because your myscore is declared inside myFunction() so it always start at 0 and plus 1 when a checkbox checked. Move it outside the function will solve it.
Or if you just want to get the amount of checked checkbox, document.querySelectorAll('input:checked').length may help.
Demo:
var myscore = 0;
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo1").innerHTML = document.querySelectorAll('input:checked').length;
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
<div id="demo1"></div>
You need to set (var myscore = 0) outside of the function
Refactor JS portion below the way you want or build on top of it
The for loop checks to see if the checkbox is true or false - with each time adding +1. That sum is added to a variable and pushed back to the DOM.
Codepen Demo: https://codepen.io/aystarz52/pen/JQVzKz?editors=1111
HTML
Check what applies to you: <br />
<label>Are you a boy?<input type="checkbox" id="myCheck"></label><br />
<label>Are you a girl?<input type="checkbox" id="myCheck1"></label><br />
<label>Are you a car?<input type="checkbox" id="myCheck2"></label><br />
<label>Are you a dog?<input type="checkbox" id="myCheck3"></label><br />
<hr />
<label><button class="checks" onclick="checks()">Check Checkbox</button></label>
<div id="answered"></div>
<label><button class="unchecked" onclick="uncheck()">Uncheck Checkbox</button></label>
<div id="missed"></div>
<label><button class="finalscore" onclick="myFunction()">Final Score</button></label>
<div id="demo"></div>
Style
.hide {
display: none;
}
Javascript
var myscore = 0;
var missed = 0;
var answered = 0;
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var array1 = [myl, myl1, myl2, myl3];
function myFunction() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = "You scored " + myscore + " Out Of 4";
document.querySelector(".finalscore").className += " hide";
}
}
function checks() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
answered += 1;
}
document.getElementById("answered").innerHTML = "You answered " + answered + " Out Of 4";
document.querySelector(".checks").className += " hide";
}
}
function uncheck() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == false) {
missed += 1;
}
document.getElementById("missed").innerHTML = "You missed " + missed + " Out Of 4";
document.querySelector(".unchecked").className += " hide";
}
}

What is the best way to combine and evaluate user input through javascript?

(I'm very new to this, please bear with me)
I'm making several modules that require user input and I want to somehow combine the input to produce an output. I was thinking of assigning each option a value and adding them together and creating an if/else statement to determine the output...
For example, if the user selects three options with values 1, 2, 3 and the statement says that any combined value greater than 5 will get a result of "Good", then the selected options will get a response of "Good" because when combined, they equal 6 (which is >5).
Does anyone know a better way, and/or can you direct me to some reference sites that might have what I'm looking for?
Thank you so much!! Any help is appreciated!!
Are you looking for something like this?
<form id="module1">
<input name="option1" type="checkbox" value="Orange"> Orange
<input name="option2" type="checkbox" value="Banana"> Banana
<input name="option3" type="checkbox" value="Apple"> Apple
<input name="option4" type="checkbox" value="Mango"> Mango
<input name="option5" type="checkbox" value="Pineapple"> Pineapple
</form>
<button id="evaluate" type="button">Evaluate</button>
<h4 id="result"></h4>
<h5 id="values"></h5>
<script type="text/javascript">
$(document).ready(function () {
var scoreConstants = {
'Mango': 100,
'Banana': 100,
'Pineapple': 200,
'Orange': 50,
'Apple': 250
};
var evalScore = function (selectedValues) {
var totalScore = 0;
$.each(selectedValues, function (k, v) {
totalScore += scoreConstants[v];
});
return totalScore;
}
var getScoreLabel = function (score) {
var scoreValue = 'Score: ';
if (score < 200) {
scoreValue += 'Average';
} else if (score >= 200 && score < 500) {
scoreValue += 'Good';
} else if (score >= 500) {
scoreValue += 'Excellent!';
}
return scoreValue;
}
$('body').on('click', '#evaluate', function (e) {
var $selectedValues = $('#module1').find('input:checked');
var selectedValues = [];
$selectedValues.each(function (k, v) {
var $selected = $(v);
selectedValues.push($selected.val());
});
var score = evalScore(selectedValues);
var scoreLabel = getScoreLabel(score);
var valueString = 'Selected: ';
if (selectedValues.length > 0) {
$.each(selectedValues, function (k, v) {
if (k === (selectedValues.length - 1)) {
valueString += v;
} else {
valueString += v + ', '
}
});
} else {
valueString += 'None';
}
var $result = $('#result');
$result.html(scoreLabel);
var $displayValues = $('#values');
$displayValues.html(valueString);
});
});
</script>
See the code working here:
https://jsfiddle.net/0x2L0dek/1
I think you are looking for this.
To see the result, check your console.
<input type="checkbox" class="chk" value=1>1</input><br>
<input type="checkbox" value=2 class="chk">2</input><br>
<input type="checkbox" value=3 class="chk">3</input><br>
<input type="checkbox" value=4 class="chk">4</input><br>
<button id="button1" onclick="checkSum()">Submit</button>
<script>
function checkSum(){
var chk = document.getElementsByClassName('chk');
sum = 0;
for(var i=0; chk[i]; ++i){
if(chk[i].checked){
sum = sum + parseInt(chk[i].value);
}
}
console.log(sum);
if(sum > 5){
console.log("Good");
}
}
</script>

Border outline keeps reverting to original a second after being changed in js

you're help would be appreciated with this simple but mind boggling question.
I have a contact form on which the user click submit, will run a vigorous error checking function I hard-coded myself. The error checking will aplly a red border around every form element that doesn't pass the validation test followed by an alert pop up telling the user a detailed list of where the error is located and what the error is. This all works fine except for the border on each form element being set to red. It works for a split second, long enough for you to see, before strangely reverting back to the original border colour. What on Earth is going on? It is as if there is something else over-riding this code???
Another issue discovered
I also just discovered that it doesn't alert the user like it is supposed to when all the boolean check variables are true. I even ran this alert(fnameCheck + ", " + lnameCheck + ", " + emailCheck + ", " + topicCheck + ", " + messageCheck + ", " + termsAndConsCheck); and the alert just didn't show. There is something going on here... and I don't think it is that function. I could be wrong but I have used this function elsewhere and it worked (although it had less boolean variables to check)
Here is the code...
<div class="body" style="height:560px"> <!-- This is the body --><br />
<span style="font-size:50px">Contact Us</span><br />
<div style="margin-left:20px; text-align:left">
Please feel free to enter your details below to contact us.<br />
<span style="font-size:14px; color:grey">* = required field</span><br /><br />
<form name="contactForm"> <!-- This is a form -->
First name*:<br />
<input name="fname" type="text"><br />
Last name*:<br />
<input name="lname" type="text"><br />
Email*: <br /><input name="email" type="text"><br /><br />
My comment/ enquiry concerns*:<br />
<select id="topic">
<option value="Select a topic" selected>Select a topic</option>
<option value="Billing Questions">Billing Questions</option>
<option value="Returns/ Exchanges">Returns/ Exchanges</option>
<option value="Website Enquiries">Website Enquiries</option>
<option value="Product Enquiries">Product Enquiries</option>
<option value="Other">Other</option>
</select><br /><br />
Message*:<br /><textarea id="message"></textarea>
<br /><br />
If you'd like to send us a file, you may do so below but ensure that the file is no larger than 50MB.
<br /><input type="file" name="myFile">
<br><br />
You agree to the Privacy Policy (click to confirm)*.
<input name="tandc" type= "checkbox"><br /><br />
<button onclick="submitForm()">Hi</button>
<input type="reset" value="Reset">
</form>
</div>
</div>
Here is ALL of the Javascript (all of it isn't relevant but there may be something else in here causing the issue)
<script>
document.getElementById("cover").style.display = "none";
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var username="";
function checkCookie() {
username = getCookie("username");
if (username != "") {
document.getElementById("topnavbar").innerHTML = "Welcome, " + username + ". | ";
}
}
checkCookie();
/* THIS IS THE RELEVANT STUFF FROM HERE DOWN TO THE NEXT COMMENT */
var topic = "Select a topic";
document.getElementById('topic').addEventListener("change", function() {
switch(this.value){
case "Select a topic":
topic = "Select a topic"
break;
case "Billing Questions":
topic = "Billing Questions"
break;
case "Returns/ Exchanges":
topic = "Returns/ Exchanges"
break;
case "Website Enquiries":
topic = "Website Enquiries"
break;
case "Product Enquiries":
topic = "Product Enquiries"
break;
case "Other":
topic = "Other"
break;
}
});
function submitForm(){
var firstName = contactForm.fname.value;
var lastName = contactForm.lname.value;
var email = contactForm.email.value;
var message = contactForm.message.value;
var fnameCheck = false;
var lnameCheck = false;
var emailCheck = false;
var topicCheck = false;
var messageCheck = false;
var termsAndConsCheck = false;
var errorMsg = "";
if(isNaN(firstName)&&firstName!=""){
fnameCheck = true;
}else{
fnameCheck = false;
if(fnameCheck == ""){
errorMsg += "First Name - The field is empty \n";
}else{
errorMsg += "First Name - Please ensure it contains no numbers or symbols \n";
}
}
if(isNaN(lastName)&&lasttName!=""){
lnameCheck = true;
}else{
lnameCheck = false;
if(lnameCheck == ""){
errorMsg += "Last Name - The field is empty \n";
}else{
errorMsg += "Last Name - Please ensure it contains no numbers or symbols \n";
}
}
if(email.indexOf("#") == -1 || email == ""){
emailCheck == false;
if(email == ""){
errorMsg += "Email - The field is empty \n";
}else{
errorMsg += "Email - This is not a valid email address\n";
}
}else{
emailCheck = true;
}
if(topic == "Select a topic"){
topicCheck = false;
errorMsg += "Topic - Please select a topic \n";
}else{
topicCheck = true;
}
if(message == ""){
messageCheck = false;
errorMsg += "Message - Please enter a message \n";
}else{
messageCheck = true;
}
if(!contactForm.tandc.selected){
termsAndConsCheck = false;
errorMsg += "Terms and Conditions - Please tick the checkbox \n";
}else{
termsAndConsCheck = true;
}
if(fnameCheck && lnameCheck && emailCheck && topicCheck && messageCheck && termsAndConsCheck){
alert("form submitted!");
}else{
if(!fnameCheck){
contactForm.fname.style.borderColor = "red";
}
if(!lnameCheck){
contactForm.lname.style.borderColor = "red";
}
if(!emailCheck){
contactForm.email.style.borderColor = "red";
}
if(!topicCheck){
document.getElementById("topic").style.borderColor = "red";
}
if(!messageCheck){
contactForm.message.style.borderColor = "red";
}
if(!termsAndConsCheck){
contactForm.tandc.style.outline = "1px solid red";
}
alert("Please fix the fields listed below... \n\n" + errorMsg + "\nThank you.");
}
}
/* THIS IS THE END OF THE RELEVANT CODE */
</script>
<script type="text/javascript" src="./jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#slider").animate({
"left": $(".item:first").position().left + "px",
"width": $(".item:first").width() + "px"
}, 0);
$(".item").hover(function() {
$("#slider").stop();
$("#slider").animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);
});
$(".item").on("mouseout", function() {
$("#slider").stop();
$("#slider").animate({
"left": $('#four').position().left + "px",
"width": $('#four').width() + "px"
}, 500);
});
});
</script>
All I needed to do was change the line
<button onclick="submitForm()">Hi</button>
to
<button type="button" onclick="submitForm()">Submit</button>
Thank you for everybody's help!!!
It looks to me like it's working, but you're not preventing the form from submitting if there are errors. The highlights are happening, the message box pops up, but then the form submits and you lose it all.
Change your button to:
<button type="button" onclick="submitForm()">Hi</button>

Getting error [object HTMLCollection]

I am having a problem in making a simple test in javascript. This is a quick example. Each question's div id is incremented in the html code.
HTML
<form action="#">
<div id="q1">
<label>Q. ABCD</label>
<label><input type="radio" name="radio1" value="1">A</label>
<label><input type="radio" name="radio1" value="2">B</label>
<label><input type="radio" name="radio1" value="3">C</label>
<label><input type="radio" name="radio1" value="4">D</label>
</div>
....
....
<input type="button" value="Click to Submit" onClick="result();">
</form>
JS (say for 10 questions)
function result() {
var answer = new Array();
for(var i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).getElementsByTagName("input");
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
I am getting an error [object HTMLCollection] every time I submit the code. How should I do this so that I can get the value of each answer given inside the array and if someone doesn't answer any question, the array must get 0 value at its place instead of undefined. I need a pure JS and HTML solution.
Try this one
function result() {
var answer = new Array();
// there is no answer 0
answer[0] = 'unused';
for(var i=1; i<11 ; i++) {
// check if the id exists first
var container = document.getElementById("q" + i);
if(container) {
// get the selected radio checkbox
var input = container.querySelector("input:checked");
// if there's one selected, save it's value
if(input) {
answer[i] = input.value;
}
else {
answer[i] = 0;
}
}
}
console.log(answer);
}
a working fiddle - http://jsfiddle.net/dtpLjru1/
In your code, you are trying to store the HTML collection by using getElementByTagName(). This method will return all the Tags with the name of "input", so total of 4 tags as per the code above.
Instead of that, you can modify your code like below.
Assuming, you want to store "1" in case radio button is checked. else 0
function result() {
var answer = new Array();
for (var i = 1; i <= 4 ; i++) {
if (document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).checked ? 1 : 0;
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
Have not tested the code, How about we do this ?
function result() {
var answer = new Array();
for(i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
document.write( document.getElementById("q" + i).getElementsByTagName("input") );
}
else {
document.write(0);
}
}
}

Javascript to alert a user that the same info has already been entered

First I should say I am a javascript newbie so forgive my ignorance.
I'm creating a form that has three functions and also uses array:
Add - To accept a name (if field left blank it should ask the user to enter a name in an alert box)
Find - To verify a name has not already been entered (in an alert box)
List - To list the names that have been entered (in an alert box)
I have the list function working (good). The alert to enter a name comes up after you enter a name as well as when you leave the field blank (not good)
and I can't get the find function to work at all.
My code is below and I've tried so many iterations and searched so many sites for help, also tried firebug; I'm hoping someone can point me in the right direction.
Untitled
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
You have done it almost, but some lil errors.. here you can check it jsfiddle
HTML:
<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>
JS:
$(".add_button").live("click", function(){
add()
});
$(".list_button").live("click", function(){
list()
});
$(".find_button").live("click", function(){
find()
});
var a = new Array();
function list()
{
var s = "";
for(i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
if (myTextField.value == "")
{
alert ("Please enter a name");
return false;
}
myTextField.value = "";
}
function find()
{
//If the name already exists you should get a warning
var status = true;
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
{
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
status = false;
break;
}
}
if(status==true)
{
a[a.length] = myTextField.value;
}
myTextField.value = "";
}
The code had a couple of errors, here's a working version: http://jsfiddle.net/sAq2m/2/
html:
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="listItems()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
js:
var a = [];
function listItems()
{
var s = "";
for(var i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
return false;
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
var v = myTextField.value
if (!v){
v = prompt("You have not entered a name, please enter one.");
}
a.push(v);
console.log(a);
myTextField.value = "";
return false;
}
function find()
{
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
return;
}
}

Categories

Resources