Script counting unchecked form elements - javascript

In my script, a few things are happening and I'm not sure why:
If someone skips Q2, I get a console error.
If someone answers only Q2 (skips Q1 and/or Q3), it counts the value of Q2 twice.
Is there something I should have in here that indicates to skip things if they aren't checked? I thought that's in there with the first if statement? (i.e., form.q2[i].checked)
function process() {
var okay = 0;
var bad = 0;
var form = document.myForm;
var i = 0;
for (i = 0; i < form.q2.length; i++)
if (form.q2[i].checked) value = form.q2[i].value;
if (value == "1") {
bad++;
}
if (value == "2") {
bad++;
}
if (value == "3") {
okay++;
}
for (i = 0; i < form.q3.length; i++)
if (form.q3[i].checked) value = form.q3[i].value;
if (value == "1") {
bad++;
}
if (value == "2") {
bad++;
}
if (value == "3") {
okay++;
}
var out = "bad";
i = bad;
if (okay > i && document.getElementById('q1').value=="0") {out = "bad"; i=bad;}
if (okay > i && document.getElementById('q1').value=="1") {out = "okay"; i=okay;}
if (bad >= i && document.getElementById('q1').value=="0") {out = "bad"; i=bad;}
if (bad >= i && document.getElementById('q1').value=="1") {out = "okay"; i=okay;}
console.log(bad);
console.log(okay);
// location.href = out;
}
function err(msg, url, line) {
location.href = "error.html";
}
<form name="myForm">
<b>How are you feeling?</b><br>
<input type="radio" name="q1" id="q1" value="0">Bad<br>
<input type="radio" name="q1" id="q1" value="1">Good<br><br>
<b>Question 1</b><br>
<input type="radio" name="q2" value="1">Answer 1<br>
<input type="radio" name="q2" value="2">Answer 2<br>
<input type="radio" name="q2" value="3">Answer 3<br><br>
<b>Question 2</b><br>
<input type="radio" name="q3" value="1">Answer 1<br>
<input type="radio" name="q3" value="2">Answer 2<br>
<input type="radio" name="q3" value="3">Answer 3<br><br>
<input type="button" value="Show Results" onclick="process();">
<br>
<br>
</form>

You never declare the value variable. The only time it is assigned a value is inside of this for loop when you are checking question 2:
for (i = 0; i < form.q2.length; i++)
if (form.q2[i].checked) value = form.q2[i].value;
When you check value on the next line, it will only have a value if question 2 was answered. Otherwise it will be undefined
Declare the variable above with your others and give it an initial value:
var okay = 0;
var bad = 0;
var form = document.myForm;
var i = 0;
var value = 0;
The reason question 2 is counted twice is because you assign a value to value if question 2 is answered. Even though the for loop for question 3 never runs, the variable value still has the value it had from question number 2. So, the counter will be incremented again unless you reset the value of value to 0 or use a different variable to track the value for each question
function process() {
var okay = 0;
var bad = 0;
var form = document.myForm;
var i = 0;
for (i = 0; i < form.q2.length; i++)
if (form.q2[i].checked) value = form.q2[i].value; // value gets set here if question 2 is answered
if (value == "1") {
bad++;
}
if (value == "2") {
bad++;
}
if (value == "3") {
okay++;
}
for (i = 0; i < form.q3.length; i++)
if (form.q3[i].checked) value = form.q3[i].value;
if (value == "1") { // value here still has value from question 2 if for loop above is skipped
bad++;
}
if (value == "2") {
bad++;
}
if (value == "3") {
okay++;
}

Related

Why is Javascript equating 5 == 8 as true?

So I have 2 check-boxes:
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
for (var i = 0; i < statusList.length; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
When I click a checkbox it adds it to a JavaScript list, if it's already in the list I want to overwrite it with another value (123 in this example).
But when I click the second one (doesn't matter the order, the 2nd element is always 123 for some reason.
Where as I would expect if I click the top check-box it would be a list containing '5', then clicking the second check-box I would expect 5,8 but it alerts as 5,123, don't really see why it's doing this as 5==8 is false... any ideas?
Updated algorithm to fix underlying issue:
In-case anyone ever finds this useful I changed the algorithm to a better alternative:
var statusList = [];
function updateStatusString(x) {
if (statusList.length > 0) {
if (statusList.includes(x)) {
var idx = statusList.indexOf(x);
if (idx != -1) {
statusList.splice(idx, 1);
}
}
else {
statusList.push(x);
}
} else {
statusList.push(x);
}
alert(statusList);
}
first iteration:
since status list is empty you are adding 5 in it,
second iteration:
statulsList = [5]
you are adding 8 so now the statusList value is [5,8] which means also the length is 2,
so we have a third iteration which in this case 8 === 8 .
if you want to have it different save the length of the status list before adding the other item on the list.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
var lengthStat = statusList.length;
for (var i = 0; i < lengthStat; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
if(! (statusList.indexOf(x) != -1))
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
Because you are iterating over the statusList. At first iteration you check if 5 == 8, then moves to else part and inserts 8 in statusList. Your statusList is = [5, 8]. For next iteration, this becomes true statuslist[i] will be 8 and 8===8 and your statement - statusList[i] = 123; will replace last inserted 8value with 123. Therefore, your statusList array will have ["5", 123].
var statusList = [];
function updateStatusString(x) {
const input = parseInt(x);
if (statusList != null) {
if (statusList.includes(input)) {
const idx = statusList.indexOf(input);
statusList[idx] = 123;
} else {
statusList.push(input);
}
alert(statusList);
}
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
It looks like the loop was causing your issue.
You were checking for the existence of x, which on the first loop was false
You pushed it to the array
Second loop, it existed and was replaced with 123
You can dramatically simplify your code by removing one of the if checks, and using array.prototype.includes instead of looping and checking equality.
Edit: Added a third input to demonstrate 123 being added.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.includes(x)) {
statusList[statusList.indexOf(x)] = 123;
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("5")> "Active"</label>

JavaScript, retreive values into checkbox

My for loops are fine and I got the value for both transportationOutput and trasportation2 and I want to check if both values are equal checked the right checkbox input, but it does not get into if condition and I do not know why, I try to replace the == to === but also it does not work
trasportation = "car-train" //value from database
var trasportation2 = document.getElementsByName("transportation");
var transportationOutput = trasportation.split("-");
for (var i = 0; i < transportationOutput.length; i++) {
for (var j = 0; j < trasportation2.length; j++) {
if (trasportation2[j].value == transportationOutput[i]) {
trasportation2[j].checked = true;
}
}
}
<label>transportation</label>
<input type="checkbox" id="localTransportID" name="transportation" value="car"> car
<input type="checkbox" id="localTransportID" name="transportation" value="bus"> bus
<input type="checkbox" id="localTransportID" name="transportation" value="train"> train
<input type="checkbox" id="localTransportID" name="transportation" value="airplane"> airplane

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>

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);
}
}
}

Trouble setting and adding array values javascript

I want to give each check box an integer value and then if the box is checked add the values and display the total in a text box with the ID="options". So far the code is not sending a value to the desired location. Any instruction on how to improve the code would be helpful. Thank you.
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input"),
result = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += inputs[i].value;
document.getElementById("options").value = result;
}
}
}
getOptions();
</script>
You may need to attach onchange event handlers to the checkboxes as shown below. And you should parse inputs[i].value to a number using parseFloat() before adding it to result.
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input");
function getOptions() {
var result = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += parseFloat(inputs[i].value);
}
}
document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox") {
inputs[i].onchange = function () {
getOptions();
}
}
}
getOptions();
JSFiddle

Categories

Resources