Why is Javascript equating 5 == 8 as true? - javascript

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>

Related

Script counting unchecked form elements

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

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>

How to replace an value in an array with checkboxes jQuery

I'm trying to arrange a checkbox array with jQuery. I have managed to get the values to add to the array in order and remove the correct one, but for the life of me i cannot get it to replace the removed value with the newly selected value. Currently it just adds the new value to the end of the array.
Here's my code so far:
var array = [];
$('input[type="checkbox"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
$('#ff_elem512').val(array);
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
$('#ff_elem512').val(array);
}
}
}
console.log(array);
});
Thanks in advance
Use Jquery is function instead of attr like Below
var array = [];
$('input[type="checkbox"]').click(function () {
if ($(this).is('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
$('#ff_elem512').val(array);
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
$('#ff_elem512').val(array);
}
}
}
console.log(array);
});
var array = [];
$('input[type="checkbox"]').change(function() {
if ($(this).prop('checked')) {
// Add the new element if checked:
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
}
} else {
// Remove the element if unchecked:
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()), 1);
}
}
$('#ff_elem512').val(array.join(", "));
console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />One
<input type="checkbox" value="2" />Two
<input type="checkbox" value="3" />Three
<input type="checkbox" value="4" />Four
<input type="checkbox" value="5" />Five
<br />
<input type="text" id="ff_elem512" />
You can always set your array when you click some checkbox, like this:
$('input[type="checkbox"]').click(function () {
array = [];
$("input[type=checkbox]:checked").each( function () {
array.push($(this).val());
});
console.log(array);
});
Here is a fiddle: https://jsfiddle.net/9ssyxvv2/
UPDATE: If you want to preserver the clicked order, use this instead:
$('input[type="checkbox"]').click(function () {
var elem=$(this);
if (this.checked) {
array.push($(this).val())
} else {
array = array.filter(function(x){
return x != $(elem).val() });
}
console.log(array);
});

Populate input field with checkboxes jQuery

I am trying to populate two text fields with checkbox values. It will get the min and max data attribute values from the checkboxes, find the highest and lowest numbers, and set input fields with this values. If all checkboxes are unchecked, default values will be set.
For example if 50-100 and 200-300 options are checked, min input will be set to 50 and max input field will be set to 300
var lowest = +Infinity;
var highest = -Infinity;
$("input[type='checkbox']").on('click', function () {
if ($(this).filter(':checked').length > 0) {
lowest = Math.min(lowest, parseFloat($(this).attr("data-min")));
highest = Math.max(highest, parseFloat($(this).attr("data-max")));
$("#price-min").val(lowest);
$("#price-max").val(highest);
} else {
$("#price-min").val(1);
$("#price-max").val(150000);
}
});
here is my html :
<input id="price-min" type="text" value="0">
<input id="price-max" type="text" value="0"><br><br>
<input type="checkbox" data-min="50" data-max="100">50-100<br>
<input type="checkbox" data-min="100" data-max="200">100-200<br>
<input type="checkbox" data-min="200" data-max="300">200-300
https://jsfiddle.net/fpooysad/
In the change event of :checkbox take all checked min and max value in two array using map() method and then sort these two array using sort().
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="price-min" type="text" value="0">
<input id="price-max" type="text" value="0">
<br>
<br>
<input type="checkbox" data-min="50" data-max="100">50-100
<br>
<input type="checkbox" data-min="100" data-max="200">100-200
<br>
<input type="checkbox" data-min="200" data-max="300">200-300
<script>
$("input[type='checkbox']").change(function () {
var min = $('input:checkbox:checked').map(function () { return $(this).data('min') }).get().sort(function (a, b) { return a - b });
var max = $('input:checkbox:checked').map(function () { return $(this).data('max') }).get().sort(function (a, b) { return b - a });
if (min.length) {
$("#price-min").val(min[0]);
$("#price-max").val(max[0]);
} else {
$("#price-min").val(1);
$("#price-max").val(150000);
}
});
</script>
$(document).ready(function () {
$("input[type='checkbox']").on('click', function () {
var allChecked = $("input[type='checkbox']").filter(':checked');
if (allChecked.length > 0) {
var lowest = null;
var highest = null;
allChecked.each(function() {
var low = parseFloat($(this).attr("data-min"));
var high = parseFloat($(this).attr("data-max"));
if (lowest == null || low < lowest) {
lowest = low;
}
if (highest == null || high > highest) {
highest = high;
}
});
$("#price-min").val(lowest);
$("#price-max").val(highest);
} else {
$("#price-min").val(1);
$("#price-max").val(150000);
}
});
$(document).ready(function () {
$("input[type=checkbox]").click(function() {
var maxArr = [], minArr = [];
var getMax = 15000, getMin = 0;
$("input[type=checkbox]:checked").each(function() {
var getIndMax = $(this).attr("data-max");
var getIndMin = $(this).attr("data-min");
maxArr.push(getIndMax);
minArr.push(getIndMin);
});
if(minArr.length) {
getMin = Math.min.apply(null, minArr);
}
if(maxArr.length) {
getMax = Math.max.apply(null, maxArr);
}
$("#price-min").val(getMin);
$("#price-max").val(getMax);
});
});
https://jsfiddle.net/fpooysad/2/
Terms Utilized
.push is used in order to add a value in an array, in this case array vars are maxArr and minArr
Math.min & .max is to consider max and minimum values within an array
This must help you out
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
var lowest =+Infinity;
var highest = 0;
$.each($("input[type='checkbox']:checked"),function(){
lowest = parseInt($(this).data("min")) < lowest ?parseInt($(this).data("min")) : lowest;
highest = parseInt($(this).data("max")) > highest ?parseInt($(this).data("max")) : highest;
});
if (lowest ==0 && highest ==0) {
$("#price-min").val(1);
$("#price-max").val(150000);
} else {
$("#price-min").val(lowest);
$("#price-max").val(highest);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="price-min" type="text" value="0">
<input id="price-max" type="text" value="0">
<br>
<br>
<input type="checkbox" data-min="50" data-max="100">50-100
<br>
<input type="checkbox" data-min="100" data-max="200">100-200
<br>
<input type="checkbox" data-min="200" data-max="300">200-300
And here is Working JSfiddle

Checking radio buttons according to an Array

I have an array containing four numbers:
var players = [0,3,4,2];
I have some radio buttons to select a name:
<h3 id="question">Which player would you like?</h3>
<input type="radio" name="choice" value="0" id="answ1">
<label for="choice" id="choice_1">John</label>
<br>
<input type="radio" name="choice" value="1" id="answ2">
<label for="choice" id="choice_2">Wayne</label>
<br>
<input type="radio" name="choice" value="2" id="answ3">
<label for="choice" id="choice_3">Steven</label>
<br>
<input type="radio" name="choice" value="3" id="answ4">
<label for="choice" id="choice_4">Jack</label>
<br>
<button id="back">Back</button>
<button id="next">Next</button>
When the radio buttons display I would like the first radio button to be checked i.e. The player John. I know I could simply set autofocus or use jQuery but I want to do it with vanilla Javascript. The idea is that the player names will change dynamically and the player will be selected based on the value in the array i.e. number 3 of the second set of players will be chosen.
Thanks, any help appreciated.
EDIT:
John will be chosen because the first value of the array is 0 and John is the first choice i.e. 0 = 1st choice, 1 = second choice etc
You need to increment/decrement an index value when the Next/Back buttons are clicked, and then set the checked property to true for the radio button with that index.
var players = [0, 3, 4, 2, 1];
var i = 0;
var choices = document.querySelectorAll('input[name="choice"]');
choices[players[i]].checked = true;
document.getElementById('back').onclick = function () {
if (i > 0) {
i--;
choices[players[i]].checked = true;
}
}
document.getElementById('next').onclick = function () {
if (i < players.length - 1) {
i++;
choices[players[i]].checked = true;
}
}
DEMO
You can try my approach using array.indexOf
var players = [0, 3, 4, 2];
var ins = document.getElementsByName('choice');
for (var i = 0; i < ins.length; i++) {
if (players.indexOf(parseInt(ins[i].value, 10)) > -1) {
ins[i].checked = true;
}
}
FYI:
The radio button is grouped under the name check so multiple
select is not going to work in your case.
This code will fail in older version of IE and here is the workaround.
You can do this like this:
var players = [0,3,4,2];
var firstValue = players[0];
var firstInput = document.querySelector("input[type=radio][name=choice][value='"+firstValue+"']");
firstInput.checked = true;
var players = [0,3,1,2];
var currentPosInArray = 0;
window.onload = function() {
ChangeSelectedRadio();
}
function ChangeSelectedRadio() {
var radio = document.querySelectorAll("input[type='radio']");
var arrItem = players[currentPosInArray];
for (var i =0; i< radio.length; i++ ){
radio[i].checked = false;
}
if (radio[arrItem]) {
radio[arrItem].checked = true;
}
}
function ChangeSelection(forward) {
if (forward) {
currentPosInArray++;
}
else {
currentPosInArray--;
}
if (currentPosInArray < 0) {
currentPosInArray = players.length -1; //if is in first pos and click "Back" - go to last item in array
}
else if (currentPosInArray >= players.length) {
currentPosInArray = 0; //if is in last position and click "Next" - go to first item in array
}
ChangeSelectedRadio();
}
where ChangeSelection(forward) is event to buttons.
DEMO: http://jsfiddle.net/9RWsp/1/

Categories

Resources