input field displaying NaN - javascript

Description
Hi, I am using knock out. I have three checkboxes and an input field. When I click on checkbox, the value of the checkbox should appear on the input field. However, instead of getting the value of the checkbox, I see NaN.
jsFiddle link
function ViewModel() {
var self = this;
self.primaryClass = ko.observable("50");
self.secondaryClass = ko.observable("40");
self.otherClass = ko.observable("10");
self.selectedValues = ko.observableArray([]);
self.sum = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(self.selectedValues(), function (item) {
total += parseInt(item);
});
return total;
});
}
ko.applyBindings(new ViewModel());

Looking at the code, on this line,
total += parseInt(item);
the variable item is the value of your checkboxes.
<input data-bind="checked: selectedValues" type="checkbox" value="primaryClass">500</input>
<input data-bind="checked: selectedValues" type="checkbox" value="secondaryClass">200</input>
<input data-bind="checked: selectedValues" type="checkbox" value="otherClass">100</input>
meaning you are trying to parseInt("primaryClass") ... and so on.
Try changing the value of the checkbox to numbers.
Like here: http://jsfiddle.net/2L4W9/

Check this out:
http://jsfiddle.net/Dtwigs/uFQdq/5/
Do your inputs like this to make them dynamic:
<label>
<input data-bind="checked: selectedValues, value: primaryClass" type="checkbox"></input>
<span data-bind="text: primaryClass"></span>
</label>
Change your values to the values in text.

Related

Dynamically loop through checkboxes and get their value and isChecked

I am dynamically printing out checkboxes depending on list from database, called in the code 'coachProperties'. Each coachProperty will get their own checkbox appended with the text which is unique.
I want to add this to another object 'properties'. Something like 'properties{text1 : "false, text2 : "true"} to then later on take it to server-side to do some filtering. I dont want any sumbit button since i want it to dynimcally update which i have js code for. All values in 'properties' will start with "false" which should update when checkbox is clicked. The problem is, sometimes when I uncheck a box it still displays as true and vice versa.
<div data-id="coachPropertiesCheckbox">
<% coachProperties.get('coachProperties').forEach(function (coachProperty) { %>
<div class="checkboxes">
<label>
<input type="checkbox" data-id="test" value="<%= coachProperty.text %>"> <%= coachProperty.text %>
</label>
</label>
</div>
<% }); %>
</div>
Js code:
function setProp(obj,prop,value){
obj[prop] = value;
};
var properties = {};
coachProperties.get('coachProperties').forEach(function (coachProperty) {
properties[coachProperty.text] = "false";
});
view.$el.find('[data-id="coachPropertiesCheckbox"] div.checkboxes input').change(function () {
var isCheckboxedChecked = view.$el.find('[data-id="test"]').is(':checked');
var valueCheckbox = $(this).attr("value");
setProp(properties, valueCheckbox, isCheckboxedChecked );
$.each( properties, function( key, value ) {
console.log( key + ": " + value );
});
});
Use value property to hold data that you would like to associate with the checkbox and do not use it to toggle true and false. Whether checkbox is checked or not, you can know from the checked property.
A piece of advice, most probably, you'll NOT want to use checkbox label same as value because values are for internal purpose, for any data manipulation, and labels have sole purpose of display in the UI.
Please try the following solution direction:
$('.checkboxes input').on('change', (event) => {
const checked = $(event.target).prop('checked')
const value = $(event.target).prop('value')
console.log(checked, ':', value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="checkbox1-id" value="checkbox-1" /><label for="checkbox1-id">Checkbox 1</label>
<input type="checkbox" id="checkbox2-id" value="checkbox-2" /><label for="checkbox2-id">Checkbox 2</label>
<input type="checkbox" id="checkbox3-id" value="checkbox-3" /><label for="checkbox3-id">Checkbox 3</label>
</div>
view.$el.find('div.checkboxes input').change(function (event) {
var id = $(event.target).attr('data-id');
if ($(event.target).prop('checked')) {
resultSetParameters.get('filter').coachProperties.push(id);
resultSetParameters.trigger('change');
} else {
var index = resultSetParameters.get('filter').coachProperties.indexOf(id);
if (index > -1) {
resultSetParameters.get('filter').coachProperties.splice(index, 1);
resultSetParameters.trigger('change');
}
}
});

jQuery Get data-attribute of all checkbox into a string

I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
Instead return $(this).val(); you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();

Count value of inputs with same name and copy final value to another input

I have i div with multiple inputs with same name:
<div class="cart_items_goes_up">
<input type="hidden" value="4" name="menu_item_id[]" class="single_menu_item">
<input type="hidden" value="3" name="menu_item_id[]" class="single_menu_item">
<input type="hidden" value="2" name="menu_item_id[]" class="single_menu_item">
</div>
I need to count all these values of the input with name menu_item_id[] and copy the result value to another input with class "order_sum".
I know how to take all values into an array but don't know how to sum them and copy to my new input.
My progress:
jQuery(".cart_items_goes_up input[name='menu_item_id[]']").map( function() {
return jQuery(this).val();
} ).get();
Any idea? Thank you
You're not too far, just that the approach you too would have you go through two loops. Therefore, rather than use map, use each:
var sum = 0;
jQuery(".cart_items_goes_up input[name='menu_item_id[]']").each( function() {
sum += +this.value;
});
jQuery('input.order_sum').val( sum );
WORKING JSFIDDLE DEMO

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

I'm trying to assign a variable to check-boxes and adding that variable to an output variable when it's checked

I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.

Categories

Resources