Increase value of digit within HTML string (jQuery) - javascript

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

Related

Add together numbers in separate DIVs

(obligatory I'm new to this) What I am trying to do is...
Fetch the contents (a number) of the DIV ID.
Add those numbers together
Print them in the "at" DIV.
I know it should be pretty darn simple. But I cant wrap my head around why it isn't working. I want to learn WHY it's not working. I dont necessarily want you guys to write it for me. I want to learn. Here is my code...
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
It outputs properly, but it's just not adding the numbers in the DIVs together. It's placing them side by side rather than adding them together.
That's because you are only doing a string concatenation.
You need to transform the values to numbers as .innerHTML() returns a string. This is how should your operation:
var addopt = +ac + +ah + +af;
Note:
It's better to use .innetrText() or .textContent() over .innerHTML to avoid getting HTML markups inside your elements if there are any into the result.
This happens a lot. What you need to do is convert to integer because it reads it as a string using ParseInt (variable) or ParsefLoat (variable) ParsefLoat (variable) can also use .toFixed (decimal_places)
You have to parse the content of the divs to a number, as the innerHTML returns a string.
So either var addopt = +ac + +ah + +af; or var addopt = parseInt(ac) + parseInt(ah) + parseInt(af); should work for you.
You need to parse the innerHTML to integers or floats to be able to do mathematical operations on them. Check the below code that takes the text and parses it to ints:
var addopt = parseInt(ac) + parseInt(ah) + parseInt(af);
You try to additionnal strings instead of numbers.
innerHTML return the string in a HTML element.
You should parseInt or parseFloat the content to have numbers.
<script>
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
// Values are taken as string and mus be converted to int.
// We check also that a value is not undefined.
ac = isNaN(parseInt(ac)) ? 0 : parseInt(ac);
ah = isNaN(parseInt(ah)) ? 0 : parseInt(ah);
af = isNaN(parseInt(af)) ? 0 : parseInt(af);
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
</script>
The contents of your divs are strings, even though the represent numbers. So if your divs have the values '1', '2' and '3' adding them togther gives you '123' rather than 6 as you might expect. Have a look at the parseInt function to see how you can turn your strings into numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

How to get jQuery animateNumber to pull value dynamically?

I am trying to implement jQuery animateNumber, and I have it working like the demo just fine. However, I want to modify it so that it pulls the number from the HTML, rather than setting it in the script. I tried the following, but it just shows "NAN." What am I doing wrong?
<div class="stat-title animate-number">$16,309</div>
<script>
$('.animate-number').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = $(this).text();
value = parseInt(value);
// Set the starting text to 0
$(this).text('0');
$(this).animateNumber(
{
number: value,
},
1000
)
});
</script>
ParseInt is failing because of the $ character. Also, the comma is messing with parseInt and giving you the value 16 instead of 16309. After that, the animation seems to be working. Also, you don't necessarily have to replace it with 0 since animateNumber automatically starts from 0. Here's my work so far on JSfiddle:
http://jsfiddle.net/0m9828kn/1
$('.animate-number').each(function(){
var value = $(this).text();
value = value.substring(1, value.length);//Remove $ sign
value = value.replace(/,/g, "");//Remove all commas
value = parseInt(value);
//$(this).text("0"); //This part isn't actually necessary
$(this).animateNumber(
{
number: value
},
1000
)
});
Looks like the problem is that ParseInt is choking on the dollar sign. Then when you remove that, it only reads up to comma and animates to 16. Take them both out, and it works.
value = $(this).text().replace(/[\,\$]/g,'');
But, you'll need to include this option to get your comma back:
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator(',')
$(this).animateNumber(
{
number: value,
numberStep: comma_separator_number_step
},
1000
)
To get your dollar sign back, you could change your html to something like this:
<div>$<span class="stat-title animate-number">16,309</span></div>

How to change the current URL in javascript?

On my website:
http://mywebsite.com/1.html
I want to use the
window.location.pathname
to get the last part of the url:
1.html
and since I have all my webpages in numbers I want to add 1 to the current url so that when I click a button it will redirect me to the next page:
var url = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;
}
any ideas why this is not working ?
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
This is more robust:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
When the URL has multiple numbers, it will change the last one:
http://mywebsite.com/8815/1.html
It supports numbers with leading zeros:
http://mywebsite.com/0001.html
Example
Even it is not a good way of doing what you want try this hint:
var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

image src from a var?

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", "");

How do I get the unicode/hex representation of a symbol out of the HTML using JavaScript/jQuery?

Say I have an element like this...
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo class="symbol">α</mo>
</math>
Is there a way to get the unicode/hex value of alpha α, &#x03B1, using JavaScript/jQuery? Something like...
$('.symbol').text().unicode(); // I know unicode() doesn't exist
$('.symbol').text().hex(); // I know hex() doesn't exist
I need &#x03B1 instead of α and it seems like anytime I insert &#x03B1 into the DOM and try to retrieve it right away, it gets rendered and I can't get &#x03B1 back; I just get α.
Using mostly plain JavaScript, you should be able to do:
function entityForSymbolInContainer(selector) {
var code = $(selector).text().charCodeAt(0);
var codeHex = code.toString(16).toUpperCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
return "&#x" + codeHex + ";";
}
Here's an example: http://jsfiddle.net/btWur/
charCodeAt will get you the decimal value of the string:
"α".charCodeAt(0); //returns 945
0x03b1 === 945; //returns true
toString will then get the hex string
(945).toString(16); // returns "3b1"
(Confirmed to work in IE9 and Chrome)
If you would try to convert Unicode character out of BMP (basic multilingual plane) in ways above - you are up for a nasty surprise. Characters out of BMP are encoded as multiple UTF16 values for example:
"🔒".length = 2 (one part for shackle one part for lock base :) )
so "🔒".charCodeAt(0) will give you 55357 which is only 'half' of number while "🔒".charCodeAt(1) will give you 56594 which is the other half.
To get char codes for those values you might wanna use use following string extension function
String.prototype.charCodeUTF32 = function(){
return ((((this.charCodeAt(0)-0xD800)*0x400) + (this.charCodeAt(1)-0xDC00) + 0x10000));
};
you can also use it like this
"&#x"+("🔒".charCodeUTF32()).toString(16)+";"
to get html hex codes.
Hope this saves you some time.
for example in case you need to convert this hex code to unicode
e68891e4bda0e4bb96
pick two character time by time ,
if the dec ascii code is over 127 , add a % before
return url decode string
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2){
var dec = parseInt(hex.substr(i, 2), 16);
character = String.fromCharCode(dec);
if (dec > 127)
character = "%"+hex.substr(i,2);
str += character;
}
return decodeURI(str);
}

Categories

Resources