i have a javascript shopping basket, in which the sum is returning a NaN error,almost every time.
in the code i have
$('#add-to-basket select').selectbox();
$('#contents select').selectbox().change(function (e) {
var product = $(this).parents('.product');
var ppu = product.find('.ppu').val();
product.find('.price .wrapper .value').text($(this).val() * ppu);
var total = 0;
$('.product .price .value').each(function (index, value) {
total += new Number($(value));
});
var form = $(this).parents('form');
form.ajaxSubmit(function () {
});
$('#total .value').text(total);
});
i tried using parsefloatm but still it dosn't work...
$(value) gives you the jQuery-wrapped element, not the actual value.
You want $(value).val() instead if the elements are form inputs, or $(value).text() if not.
Also, instead of new Number(...) you should just use Number(...), or even +...:
$('.product .price .value').each(function (index, value) {
total += +$(value).val();
});
See this question for the difference between new Number and Number.
Related
I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});
How do I take the result from "#sum" and have it auto duplicated in a textfield so that when I submit a form, the value gets sent also?
<script>
$(document).ready(function() {
$(":text").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum=0;
$(":text").each(function() {
if(!isNaN(this.value) && this.value.length!=0 {
sum+=parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(0));
$("#myTextField").val(sum.toFixed(0)); //adding to text field
}
</script>
Is there a quick fix to this?
This is where the actual value updates on the HTML page.
<span id="sum">0</span>
It is not adding right. If I type in 500 in one of the fields it now takes the first number and repeats, so if I type 500 it outputs as 555
any help?
Your issue is is that ":text" is selecting myTextField. So your final value is being added back in.
5 = 5; 50 + 5 = 55; 500 + 55 = 555; You can try using the not selector.
$(":text:not('#myTextField')")
http://jsfiddle.net/RhRbR/
$(":text:not(#myTextField)").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum+=parseFloat(this.value);
}
})
The fiddle can show you the way.
My question has part solutions on this site but not a complete answer.
On my wordpress homepage I display a counter of the number of questions answered within our webapp. This is displayed using jQuery and AJAX to retrieve the question count from a php file and works fine with this code.
jQuery(document).ready(function() {
function load() {
jQuery.get('/question_count.php', function(data) {jQuery('#p1').html( data ); });
}
load();
setInterval(load,10000);
});
Is there a way to display counting up to the new number retrieved rather than just immediately displaying it?
Something like this?
function countTo(n) {
var p = $("#p1"),
c = parseInt(p.html(), 10) || 0,
dir = (c > n ? -1 : 1); // count up or down?
if (c != n) {
p.html((c + dir) + "");
setTimeout(function() {
countTo(n);
}, 500);
}
}
Call it in your success handler
jQuery.get('/question_count.php', function(data) {
var n = parseInt(data, 10);
countTo(n);
});
Example
You will need to do a setInterval event so that the count up is visable to human eyes.
This may be a problem if you eventually reach enough questions where the count takes a long time to reach the end.
Code will look like this:
function load(){
jQuery.get('/question_count.php', function(data){
var curr = 0;
var max = parseInt(data);
var interval = setInterval(function(){
if(curr==max){
clearInterval(interval);
}
jQuery('#p1').html( curr );
curr+=1; //<-- if the number of questions gets very large, increase this number
},
10 //<-- modify this to change how fast it updates
});
}
}
Hello I am getting my data from csv file and I am using 'this.update(0)' on my chart to update any point through a mouse click therefore making that point equal to 0 on y axis but what I want is that when I click on a point it first gets me the index of that point and then reload the data again from same csv file but this time the data values should not go beyond the index. e.g if I clicked on a point at x=10 then I should be able to reload the data again from file till x=9 and store the newly loaded data to an array.
Here is a part my code where data has to be reloaded. It reloads the entire data which is not need, that's probably I am not getting the right index or if there is someother problem kindly help. Thank you.
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var x= this.update(0);
$.get('testFile.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if(itemNo<x){
series.data.push(parseFloat(item)); } });
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
To get index use: this.series.processedXData.indexOf(this.x)
Now, remove creating new chart, but instead update each of points with values, something like this:
var actSeries = this.series; //needed for scope range
...
...
...
$.each(items, function(itemNo, item) {
if(itemNo<x){
actSeries.data[itemNo].update(parseFloat(item), false);
});
});
actSeries.chart.redraw();
I incorporate javascript in my PHP program:
Try to check my codes.
It loops depend on the number of records in database.
for instance:
$counter = 0;
foreach($row_value as $data):
echo $this->javascript($counter, $data->exrate, $data->tab);
endforeach;
private function javascript($counter=NULL, $exrate=NULL, $tab=NULL){
$js = "
<script type='text/javascript'>
$(function () {
var textBox0 = $('input:text[id$=quantity{$counter}]').keyup(foo);
var textBox1 = $('input:text[id$=mc{$counter}]').keyup(foo);
var textBox2 = $('input:text[id$=lc{$counter}]').keyup(foo);
function foo() {
var value0 = textBox0.val();
var value1 = textBox1.val();
var value2 = textBox2.val();
var sum = add(value1, value2) * (value0 * {$exrate});
$('input:text[id$=result{$counter}]').val(parseFloat(sum).toFixed(2));
// Compute Total Quantity
var qtotal = 0;
$('.quantity{$tab}').each(function() {
qtotal += Number($(this).val());
});
$('#tquantity{$tab}').text(qtotal);
// Compute MC UNIT
var mctotal = 0;
$('.mc{$tab}').each(function() {
mctotal += Number($(this).val());
});
$('#tmc{$tab}').text(mctotal);
// Compute LC UNIT
var lctotal = 0;
$('.lc{$tab}').each(function() {
lctotal += Number($(this).val());
});
$('#tlc{$tab}').text(lctotal);
// Compute Result
var result = 0;
$('.result{$tab}').each(function() {
result += Number($(this).val());
});
$('#tresult{$tab}').text(result);
}
function add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
if (IsNumeric(arguments[i])) {
sum += parseFloat(arguments[i]);
}
}
return sum;
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
</script>
";
return $js;
}
When I running this on IE7 this message is always annoying me
Stop running this script?
A script on this page is causing your web browser to
run slowly. If it continues to run, your computer
might become unresponsive.
but in firefox it's functioning well.
IE displays that message when it decides that a script is taking too long (actually other browsers have a similar warning, but they don't all calculate "too long" the same way and don't all run at the same speed).
You didn't actually ask a question, but I assume you want to know how to make your script more efficient so that it will (we hope) complete before that IE message is triggered?
I like jQuery a lot, but using it does involve a lot of function calls, including nested functions with callbacks, etc., and once you start putting these functions inside loops (in your case multiple loops) it can get quite inefficient. If you're only processing a small number of items this may not be noticeable to the user, but if you're processing a lot the first thing you could change that would definitely speed up your code would be changing the .each() loops to standard for loops:
// CHANGE
var qtotal = 0;
$('.quantity{$tab}').each(function() {
qtotal += Number($(this).val());
});
// TO
var qtotal = 0,
$q = $('#tquantity{$tab}');
for (i = 0; i < $q.length; i++)
qtotal += +$q[i].value;
Note that in the for loop I've used the DOM element's value property directly rather than using jQuery to retrieve it via .val() (which even within .each() you could've done with this.value rather than $(this).val()). I've also used the unary plus operator instead of Number(). This means no function calls at all on loop iterations, whereas your way had a call to Number(), $() and .val() (not even counting the additional processing that jQuery does behind the scenes within $() and .val()).
Make a similar change for all of your .each() loops (declare i at the beginning of your function and re-use it for each loop) and you should see some improvement.