javascript problem with implicitly typed variables - javascript

Forgive this novice question (novice in Javascript!).
In a html page I have a set of images with a name and a number: img1 img2 img3... img12...
And there is a JS function where I need to iterate from (say) img5 to last img.
If I write this:
function iterateImg(objImgID) {var imgNum = objImgID.replace("img","");
for (i=imgNum+1;i<20;i++)
.../...
The variable "i" is treated as a string, and i+1 receive the value "51" if the passed object's ID is img5.
Of course I can still iterate from 1 to n and only perform the desired task when the value of i reaches 6, but that would be an ugly fix.
How can I fix this please? How can I create a variable that will be treated as an integer before I use it as seed?
Besides, what would you recommend as best practice?

var imgNum = Number(objImgID.replace("img",""));
That'll do it.
Or better yet (because I love regex)
var imgNum = Number(objImgID.match(/[0-9]+/));

Use parseInt to convert the string to a number
var imgNum = parseInt(objImgID.replace("img", ""));

There are several ways to force JavaScript to convert it into a number
parseInt(x, 10) - the 10 is the base of the number
x - 0 - subtracting only works for numbers
x * 1 - multiplying also

var imgNum = parseInt(objImgID.replace("img",""), 10);
Now when you do var i=imgNum+1, it will perform addition of 2 integers.

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

Transfer random String to .innerHTML

I want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.
Can someone help me with that?
function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";
var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
How about storing all random strings in an array, like so:
function switchText(){
var randomWords = ["hello", "there", "ObiWan"];
var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = randomWords[randomIndex];
//the problem
}
Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to
document.getElementById("randomText").innerHTML = this['text' + randomNumber];
However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.
Store those texts into an array and use the random number.
Get the random number as follow: Math.floor(Math.random() * 3)
function switchText(){
var texts = ["hello", "there", "ObiWan"];
var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
You can store those texts into an object as well.
function switchText() {
var texts = {
"text1": "hello",
"text2": "there",
"text3": "ObiWan"
};
var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.
Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.
All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.
This structure and solution make your code simpler and more flexible.
Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.
var strings = ["hello","there","ObiWan"]; // Store the possible strings in an array
var btn = document.getElementById("randomText"); // Get a reference to the trigger element
var output = document.getElementById("output"); // And the output area
// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
// Set the output to a string from the array using a random index
output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>

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());

Combining retrieved values with javascript and jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?
I have a select element that contains options for products. What I want to achieve is when they pick an option the price on the page automatically adjusts. I have figured out how to retrieve those values but when I combine them it just puts two numbers together instead of actually adding them.
For example instead of outputting 60 when I have 50 + 10 it outputs 5010.
My code:
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Is there a way I can convert them both to integers so the operation actually goes through?
Thanks in advance!
Use parseInt
$('.product_options').change(function(){
var base_price = parseInt($('#base_price').html(), 10); // 10 as second argument will make sure that base is 10.
var add_price = parseInt($(this).find("option:selected").data('price'), 10);
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Try:
var base_price = +$('#base_price').html();
var add_price = +$(this).find("option:selected").data('price');
See the mighty: Mozilla's Arithmetic Operators Reference - Unary Negation
Any values you pull out of the DOM are going to be strings, and need converting into number types before you can do mathematical operations with them.
parseInt( ... ) is a built in javascript function that converts a string into an integer, if the string consists of digits only.
If you need a decimal number, you can use parseFlaot.
var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`
Use parseFloat or parseInt
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = parseFloat(base_price) + parseFloat(add_price);
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Yes there is.
intval = parseInt(string)
is what you're looking for.

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