I'm trying to do a sum of numbers inside div's, so, I did:
$(document).ready(function() {
var numbers, sumNumbers;
$(".item").each(function() {
numbers = $(this).children().text();
numbers = +numbers;
sumNumbers += numbers;
});
console.log(sumNumbers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<span class="itemNum">0</span>
</div>
<div class="item">
<span class="itemNum">2</span>
</div>
<div class="item">
<span class="itemNum">1</span>
</div>
But, same converting the numbers from text to number with +numbers is returned NaN, why? I've already tried with Number(numbers) too but the result is the same.
You didn't initialize sumNumbers, so you get undefined + a number = NaN
var numbers, sumNumbers = 0;
Try this
var numbers=0, sumNumbers=0; //initilize numbers & sumNumbers;
$(".item").each(function () {
numbers = $(this).children().text() * 1; // *1 convert string to number
sumNumbers += numbers;
});
console.log(sumNumbers);
Related
Hope I can explain well.
So I have 8 boxes with class .boxA with a numeric value generated from js:
<div class="tfooter">
<div class="boxA" id="bx3" value="3">3</div>
<div class="boxA" id="bx27" value="27">27</div>
<div class="boxA" id="bx46" value="46">46</div>
<div class="boxA" id="bx40" value="40">40</div>
<div class="boxA" id="bx42" value="42">42</div>
<div class="boxA" id="bx29" value="29">29</div>
<div class="boxA" id="bx13" value="13">13</div>
<div class="boxA" id="bx1" value="1">1</div>
</div>
First of all I push all values in a array:
var randomnumber = Math.ceil(Math.random()*50);
var array = [];
$(".boxA").each(function(){
var dNumber = $(this).attr('value');
array.push(dNumber);
});
Each of this boxes contain a random number from 1 to 50.
Now, I want to generate another random number and check if exists in the array. If exists, generate another number until it's unique in that array. When is unique, create another div.
I've tryed with indexOf, with inArray, with while, but I can't get it working. The problem is that generate. Generate new number until not in array.
Thank you very much!
You could avoid the trial-and-error method by first building an array with the allowed values (i.e. those that do not appear in the list), and then pick a random value from that.
Here is a snippet that will add a new (non-used) number at the top of the list at the press of a button:
function getUsedNumbers() {
return $(".boxA").map(function(){
return +$(this).attr('value');
}).get();
}
function getCandidates(exclude) {
// Generate a list of values from 0 to 49, and make it a Set
// (Sets allow for faster look-up and value removal)
var candidates = new Set(Array(50).keys());
for (value of exclude) {
// Remove the already used value from our Set:
candidates.delete(value);
}
// Convert Set back to array and return it:
return [...candidates];
}
function pickRandomly(array) {
return array[Math.floor(Math.random()*array.length)];
}
$('#add').click(function () {
var used = getUsedNumbers();
var candidates = getCandidates(used);
// Safety:
if (!candidates.length) {
alert('No more candidate values available');
return;
}
var choice = pickRandomly(candidates);
// Insert the selected number at the top of the list:
$(".tfooter").prepend(
$("<div>").addClass("boxA").text(choice).attr({
id: "bx"+choice, value: choice
})
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="tfooter">
</div>
If you do this repeatedly, then it is not so efficient to re-read the list of values from the page each time, since you actually know what is there already.
Consider making the candidates Set the master reference for your data, and only depend on that to generate the output.
You need to use $.inArray() to check if the random number exists in an existing array or not. if the number doesn't exist, it adds that random number to the array. Below is an updated code:
$("#generateNewNumber").on('click', function() {
var newArray = [];
$(".boxA").each(function() {
newArray.push(parseInt($(this).attr('value')));
});
var randomNumber = Math.ceil(Math.random() * 50);
console.log('Random number is: ' + randomNumber);
if ($.inArray(randomNumber, newArray) !== -1) {
console.log(randomNumber + ' exisits in array');
} else {
newArray.push(parseInt(randomNumber));
$(".tfooter").append('<div class="boxA" id="bx' + randomNumber + '" value="' + randomNumber + '">' + randomNumber + '</div>')
console.log(randomNumber + " doesn't exisits in array, hence adding in an array.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="generateNewNumber">Generate Random Number</button>
<div class="tfooter">
<div class="boxA" id="bx3" value="3">3</div>
<div class="boxA" id="bx27" value="27">27</div>
<div class="boxA" id="bx46" value="46">46</div>
<div class="boxA" id="bx40" value="40">40</div>
<div class="boxA" id="bx42" value="42">42</div>
<div class="boxA" id="bx29" value="29">29</div>
<div class="boxA" id="bx13" value="13">13</div>
<div class="boxA" id="bx1" value="1">1</div>
</div>
Here is how I would had set up the code:
Create the array with numbers 1-50 in it.
Create a random number based on the list's length.
Randomly splice a position. That position will then be removed from the array but return a an array with one item.
If the array is empty (length 0), start over at 1.
Then you don't need to check if the number exists, because it has already been removed from the array.
function createBoxNumbersArray(startNumber, endNumber) {
var boxNumbers = [];
for (var i = startNumber; i <= endNumber; i++) {
boxNumbers.push(i);
}
return boxNumbers;
}
function getRandom(boxNumbers) {
position = Math.floor((Math.random() * boxNumbers.length-1));
return boxNumbers.splice(position, 1)[0];
}
var boxNumbers = createBoxNumbersArray(1, 50);
var randomBoxNumber = getRandom(boxNumbers);
Seems like indexOf would be the way to go. Your problem is that you're probably comparing the HTML attribute value (a string) to the random number (a number).
so, once you update to:
array.push(parseInt(dNumber));
You will be able to check
if(array.indexOf(randomnumber) >= 0) { } // regenerate random
I have an issue with some piece of jquery code :)
The case is the following:
I have an array with numbers var arr.
I have a function get_number() which get each number from an
array.
I have function with parameter inner_li_height(number), which get max height of elements and set this height to other elements.
But something get crashed... :(
Here is a jsfiddle
HTML Structure
<div id="slide-1">
<div class="inner-li">
<p>Lorem Ipsum...</p>
</div>
</div>
<div id="slide-2">
<div class="inner-li">
<p>Lorem Ipsum...</p>
</div>
</div>
<div id="slide-3">
<div class="inner-li">
<p>Lorem Ipsum...</p>
</div>
</div>
Array with numbers
// Save the numbers in array
var arr = [];
$("div[id^='slide-']").each(function() {
arr.push(parseInt( $(this).attr('id').split('-')\[1] ));
});
Get each number from array
// Get each number from array
function get_number() {
$.each(arr, function(i, v) {
return arr[i];
});
}
Get maxHeight of inner-li element
// Get max-height of inner-li and set to the others with the same class
function inner_li_height(number) {
var heights = $("div[id^='slide-" + number + "'] .inner-li").map(function () {
return $(this).height();
}).get(),
maxHeight = Math.max.apply(null, heights);
console.log(maxHeight);
$("div[id^='slide-" + number + "'] .inner-li").height(maxHeight);
}
And here call the function:
// Call function inner_li_height
inner_li_height(get_number);
I'll be happy if someone can help me :)
Try this single function that works on multiple DOM objects:
// Get max-height of inner-li and set to the others with the same class
function inner_li_height(attr) {
$(attr).each(function(i,v) {
var heights = $(attr).map(function () {
return $(this).height();
}).get();
maxHeight = Math.max.apply(null, heights);
console.log(maxHeight);
$(attr).height(maxHeight);
});
}
inner_li_height('div[id^="slide-"] .inner-li');
jsfiddle: http://jsfiddle.net/hr993Lsj/1/
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
I just want the value £123 to show, need correct Javascipt to "trim" the number and not round it down or up. I've seen a few ways on here but none that target .class name, in my case .numTxt
If somebody can do me a quick fiddle I would be most appreciative!
You can use .text() call back function to modify the old text with new text:
$('li.numTxt').text(function(i,val){
return val.split(".")[0];
});
Working Demo
Here you are:
alert(document.querySelector('li').innerText.replace(/\.\d*/,''));
Hope this help.
You can do this easily with split()
var str = "£123.99"
var res = str.split(".");
//res is now an array consisting of "£123" and "99"
Working Example:
$('button').click(function(){
var str = $('#inp').val();
var res = str.split(".");
$('#output').html(res[0]);
});
input, button, div { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp" value="£123.99" />
<button>Split At Decimal</button>
<div id="output"></div>
Just use this Regex /\.\d+/:
$.fn.trimDecimal = function(){
$(this).text(function(a, text){
return text.replace(/\.\d+/,"")
})
}
$(".numTxt").trimDecimal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£83.45</li>
To truncate a decimal number, you can do it in this way:
var num = "123.99";
num = +num | 0;
console.log(num)
I need to be able to add a decimal from input to a decimal in a div. Here's my code below. Right now, it's just concatenating the two number next to each other. Thanks.
EDITED: Working code
<div id="addme">5.01</div>
<input type="text" id="anumber" value="">
<button id="add">Add Number to div</button>
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
//alert(number);
$('#addme').html(function(i, val) {
return (parseFloat(val) + number).toFixed(2);
});
});
Old Non-Working Code Below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="addme">5.01</div>
<input type="text" id="anumber" value="" />
<button id="add">Add Number to div</button>
<script type="text/javascript">
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number==''){
var number=0;
}
//alert(number);
$('#addme').html(function(i, val) {return val*1+number });
});
</script>
Since you're dealing with decimal numbers, use parseFloat():
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat(val) + number;
});
});
http://jsfiddle.net/mblase75/47t7x/
UPDATE
Since you might introduce floating-point math errors (try inputing "0.6"), you should round it to a suitable number of decimal places before returning (2 if dealing with dollars and cents; 7 or more if dealing with other measurements):
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
$('#addme').html(function(i, val) {
return parseFloat((parseFloat(val) + number).toFixed(9));
});
});
http://jsfiddle.net/mblase75/47t7x/1/
You should use parseInt() for this.
$('#addme').html(function(i, val) {return parseInt(val,10)+parseInt(number,10) });
Just make sure you're parsing the strings to actual numeric values.
function(i, val) {return parseFloat(val)*1+parseFloat(number) }
in your code it seem you want the sum, not concatenation
here is the code for sum, and you need to place that on a $(document).ready because your code was running before the objects were available.
$(document).ready(function() {
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number=='')
number=0;
var target=$('#addme');
target.html(1*target[0].innerHTML+1*number);
});
});
if you want concatenation just remove the 1*
To convert string to number you can use the trick with + before string value. It will convert string value to numeric. This code works fine:
$('#add').click(function() {
var number = +$('#anumber').val() || 0;
$('#addme').html(function(i, val) {
return (+val + number).toFixed(2);
});
});
DEMO: http://jsfiddle.net/K9g49/
// On the click event of #add
$('#add').on("click", function(){
// n is equal to #anumber, or 0 if #anumber is blank
var n = $('#anumber').val() || 0
// Determine new HTML content for #addme
$('#addme').html(function(i,v) {
// Return the sum of n and v floated, to two decimal places
return ( parseFloat(n) + parseFloat(v) ).toFixed(2);
});
});
Fiddle: http://jsfiddle.net/G8nka/1/
I am having a bunch of div tags in my html page. Now I need to write a jQuery to calculate the grid's value. In the below example I will be using grid0 as the base id and I want the count in that series which is 1 here.
<div id="grid00">0</div>
<div id="grid01">0</div>
<div id="grid02">0</div>
<div id="grid03">1</div>
<div id="grid04">0</div>
<div id="grid05">0</div>
In another example given below I will be using id's starting with grid1 and the total value is 6. Please guide me!
<div id="grid10">5</div>
<div id="grid11">0</div>
<div id="grid12">0</div>
<div id="grid13">1</div>
<div id="grid14">0</div>
<div id="grid15">0</div>
I tried this jQuery("div[id^='grid0']"). But this is giving me all the elements. But I need the count using the value inside them.
Thanks!
Start by selecting the divs with the starts-with selector and loop through the results and tally up the text values casted to integers.
function GetSum(prefix) {
var sum = 0;
$("div[id^='" + prefix + "']").each(function(){
sum += parseInt($(this).text());
});
return sum;
}
var grid0Total = GetSum("grid0");
var grid1Total = GetSum("grid1");
Or if you wanted to take it a step further with a jQuery function:
jQuery.extend({
gridSum: function(prefix) {
var sum = 0;
if(!!prefix) {
$("div[id^='" + prefix + "']").each(function(){
sum += parseInt($(this).text());
});
}
return sum;
}
});
then you could write:
var grid0Total = jQuery.gridSum("grid0");
var grid1Total = jQuery.gridSum("grid1");
You could also use the map() function like so:
var sum = 0;
$("div[id^='" + prefix + "']").map(function(){
return sum += parseInt($(this).text());
});
return sum;
See them all in action here: http://jsfiddle.net/FpmFW/1/
Try:
function total(idPrefix) {
var total = 0;
$('div[id^="' + idPrefix + '"]').each(function() {
total += parseInt($(this).text());
});
return total;
}
var grid0total = total('grid0'),
grid1total = total('grid1');
See: http://jsfiddle.net/Au8Fr/
I'd give all grid divs one commmon class. Something like this:
<div class="grid" id="myGrids">
<div class="grid" id="grid10">5</div>
<div class="grid" id="grid11">0</div>
<div class="grid" id="grid12">0</div>
<div class="grid" id="grid13">1</div>
<div class="grid" id="grid14">0</div>
<div class="grid" id="grid15">0</div>
</div>
Now you can easily count their values:
var count=0;
$(".grid").each(function(){
count+=parseInt($(this).text())
})
You can loop through all of your grid0X divs like this:
var countOnes = 0;
$('div[id^=grid0]').each(function() {
if ($(this).text() === "1") {
++countOnes;
}
});
That finds all div elements whose ID starts with grid0 (so, grid00, grid01, etc.). The loop counts how many of them contain just the text "1", which is what I think you were after in your question; if not, the loop logic is easily manipulated.
Similarly, for grid1X, just change the selector to use 1 instead of 0.
Alternately, though, if these divs are in some kind of container, you could use a selector to find the container and then loop through its children, e.g.:
HTML:
<div id="grid0">
<div>0</div>
<div>0</div>
<div>0</div>
<div>1</div>
<div>0</div>
<div>0</div>
</div>
JavaScript:
$("#grid0 > div").each(...);
...and avoid having all those IDs.