JQuery adding number value - javascript

can someone help me debug this please???
i'm really don't know whats wrong with my code...
i'm trying to add number value to another number value.... but it does not work as i expected...instead it just add the number as a string.
Here is my demo:
(already solved)
and here is the js code:
$(document).ready(function(){
$("#map").click(function(e){
var x = parseInt((e.pageX - this.offsetLeft)) - parseInt("140");
var y = parseInt((e.pageY - this.offsetTop)) - parseInt("140");
var coor = $("#map").css("background-position").split(" ");
var cx = parseInt(coor[0].replace("px",""));
var cy = parseInt(coor[1].replace("px",""));
$("#map").stop().animate({"backgroundPosition": x+cx+" "+y+cy},"slow");
alert("X:"+x+", CX: "+cx+"\n Y:"+y+", CY:"+cy+"\n Background-pos:"+$("#map").css("background-position"));
});
});
please tell me what's wrong with it...

Put parentheses () around your arithmetic operations.
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
Otherwise, adding the whitespace string will force the JS to concatenate your numbers as a string.
Fiddle example

In your animate-Statement towards the end you set background position to:
x+cx+" "+y+cy
This is interpreted as a string, because the four +-operations are interpreted equally. You do, really, concatinate a string (" "). Thus, the entire result of this expression becomes a string and the addition is no longer an addition but a concat.
However, if you capsulate the math into parenthesis, then you should be fine. Your second-last line becomes:
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
(note the extra brackets around x+cx)

Isn't it ?
var x = parseInt((e.pageX - $(this).offset().left)) - parseInt("140");
var y = parseInt((e.pageY - $(this).offset().top)) - parseInt("140");

The following works for me:
$("#map").click(function(e){
alert(e.pageX);
alert(this.offsetLeft);
alert(parseInt(e.pageX)-parseInt(this.offsetLeft));

Related

How to change the value of innerText at a particular index?

I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);

Why do I get undefined here?

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'
The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.
Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

wanted to add two floating number which gets concatenated as string

i want to add two float number with fixed two decimal but its converted to string and get concatenated.I know its simple question but actually i'm in hurry
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
Update when i enter input as
var a=parseFloat("7,191");
var b=parseFloat("359.55");
c=(a+b).toFixed(2)
O/P:NAN
why so?
The .toFixed() method returns a string. Call it after you've performed the addition, not before.
var a=parseFloat("15.24869");
var b=parseFloat("15.24869");
var c=(a+b).toFixed(2);
After that, c will be a string too, so you'll want to be careful.
As to your updated additional question, the output is not NaN; it's 366.55. The expression parseFloat("7,191") gives the value 7 because the , won't be recognized as part of the numeric value.
Just add parenthesys to parse float the whole result string
var a=parseFloat((15.24869).toFixed(2));
var b=parseFloat((15.24869).toFixed(2));
c=a+b
doing c = a + b adds the two answers together. You might just want to turn them into a string then concatenate them.
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
var c = (a.toString() + b.toString());

syntax issue with addition in javascript

I am making some addition and substraction in my javascript, but I have strange results, I don't understanf whats wrong in my syntax:
var dy, i,diff;
dy=(lines_extrema[0]-lines_extrema[1])
for(i=1;i<=(narrow+1);i++){
// Coordinates
if(i==1) diff=(-lines_extrema[1]);
else diff=(diff+lines[(0+3*(i-2))]);
}
lines and lines_extrema are read through get methods and are real.
dy is fine, I have a real.
diff is fine for i=0 and them it returns things like that "20.9603-10.9".
What's wrong in my syntax?
Thanks
You are doing operation on string variables instead of numbers, so the addition is actually a concatenation.
To convert string to numbers, prefix them with "+". Example:
var extrema0 = +lines_extrema[0];
var extrema1 = +lines_extrema[1];
then use extrema0 and extrema1 to add/substract.

Javascript format a number asin C#

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?
var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.
UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this:
var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
a.splice(i,0,",");
var formattedNumber = a.join("") + "k";

Categories