image src from a var? - javascript

I have a var that contains a number and I want to store that in image src like:
var number = 10;
<img src="images\'+number+'.jpg">
i already have a picture with called 10.jpg
also how can I change a string to a number. for example if I use reg-exp to get a number from text how can I change it to a number ?

To set the image source you can do
var image = document.getElementById("myImage");
image.src = number + ".jpg";
You can change a string into a number using the parseInt function.
parseInt("10");
or
parseInt("10", 10);
where the second parameter is the radix representing the number system.

For the sake of time, here's the jQuery solution
var myVar = "10";
$("#myImage").attr("src",myVar+".jpg");
to convert a string to base 10 integer, #Garett's answer is usable
var myVarAsInt = parseInt("10", 10);

If your using jQuery
var number = $("#imageid").attr('src').replace(".jpg", "");

Related

Increase value of digit within HTML string (jQuery)

I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea

Removing an integer from an id

I have an id:
div id ="untitled-region-5"
I want to grab that id and remove 4 from it and then do some code with the new id.
So far I am trying something like this from reading about how to perform this:
var n = $(this).attr('id').match(/untitled-region-(\d+)/)[1];
But I don't know how to remove 4 from the integer.
It's still a string, that's why you can't easily use it in math. Some operations work, because they will implicitly convert the value to a number.
Use parseInt to explicitly do the conversion, so that you know what you have:
var n = parseInt($(this).attr('id').match(/\d+$/)[0]);
n -= 4;
var id = $("div").attr("id");
var n = parseInt(id.substring(id.lastIndexOf("-") + 1), 10);
I made a jsFiddle too: http://jsfiddle.net/YEWQQ/
<div id ="untitled-region-5">​
just take n and subtract 4
var n = $('div').attr('id').match(/untitled-region-(\d+)/)[1];
var newNumber = n-4;
$('div').attr('id','untitled-region-'+newNumber);

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Performing mathematical operations on attribute value

I am attempting to perform mathematical operations with JavaScript on values obtained from an attribute. The attribute is created via a PHP loop. I will give an example of one of the html tags containing the attributes, but keep in mind that there are many of these tags which contain unique attribute values.
The HTML:
The JavaScript(jQuery):
$("a[href^='secondary_imgs.php']").click(function(){
var pageWidth = $(window).width();
var maxshadowWidth = (Math.floor(pageWidth * 0.91808874)) - 2;
var mWidth = $(this).attr("mwidth");
var maxSecondaryWidth = mWidth + 60;
alert (maxSecondaryWidth);
if(maxSecondaryWidth <= maxshadowWidth) {
var shadowWidth = maxSecondaryWidth;
} else {
var shadowWidth = maxshadowWidth;
}
var shadowboxrel = 'shadowbox;width=' + shadowWidth;
$(this).attr('rel', shadowboxrel);
The operation doesn't seem to be working, and I have a feeling it has to do with my lack of experience using mathematical operations in javascript. In this case, I think something is wrong with my method of using the attribute value, in the mathematical operation.
For example, the above width attribute is defined as 593. I define the maxSecondaryWidth as mWidth + 60. I fired an alert to see what value I was getting. It should have been shown as 653, yet the value that is 'alerted' is 59360. Obviously I don't understand how to add, as the + is concatenating the two values, as opposed to adding them together. Could it have to do with needing to transform the attribute value from a string into an integer?
You have to convert to a number using parseInt(), otherwise + will do string concatenation:
var mWidth = parseInt($(this).attr("mwidth"), 10);
If the attribute can also be a float, use parseFloat() instead of parseInt().
Do this to make sure mwidth is a number:
var mWidth = parseInt($(this).attr("mwidth"), 10);
Otherwise, + will perform a string concatenation. Alternatively, if you need mwidth to be a floating point number, do this:
var mWidth = parseFloat($(this).attr("mwidth"));
You can do a couple things:
parseInt(mWidth, 10); // int
parseFloat(mWidth); // float
Number(mWidth); // number
otherwise javascript will believe it's a string.
Some less common conversions:
mWidth | 0; // int (javascript bitwise operations are 32-bit signed intergers)
+mWidth; // force Number
i think that you must do something safer (as it is always better);
You should check if it is a number or not:
DOM:
JS:
$("a[mwidth]").each(function(){
var $attr = $(this).attr('mwidth');
if(!isNaN($attr)){
sum += (parseInt($attr));
}
});
If you remove the condition the results will be NaN
Take a look at : http://jsfiddle.net/zVwYB/

Javascript mask

How do you format a number to show 2 decimals in JavaScript?
Something along the lines of:
format(x,"9,999.99");
You should use this :
x.toFixed(2);
or if you want to be sure it will work :
parseFloat(x).toFixed(2);
var num = 3.14159;
var fixed = num.toFixed(2);
If you want the commas depending on the locale:
var localed = num.toLocaleString();
Combining both crudely:
var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();
Use .toFixed(2):
http://www.devguru.com/technologies/javascript/17443.asp
Note this will round your number:
var i = 23.778899;
alert(i.toFixed(2));
gives you
23.78
I'm not sure if you are trying to do this to input or just for displaying text on the page. You can use the masked input plugin for jQuery if you are trying to format input.
http://digitalbush.com/projects/masked-input-plugin/

Categories

Resources