Replace numeric value with another

I have a space in my HTML as follows, which I assign text from code:

<span id="NewL1" visible="false" runat="server"><span runat="server" id="NewL"></span></span> 

The text will be something like this: "you have 3 notifications."

I want to change a numeric value in jQuery. I tried this but nothing happens:

 var notification = $("#NewL"); var numb = notification.text().match(/\d/g); var finalTotalCount = parseInt(numb) - 1; notification.text(notification.text().replace(numb, finalTotalCount )); 

What am I doing wrong?

+4
source share
3 answers

So you have this HTML code:

 <span id="NewL1" visible="false" runat="server"> <span runat="server" id="NewL">you have 3 notifications</span> </span> 

Then your current JavaScript code only works if your dynamic text you have 3 notifications inserted in the right place, that is, inside the internal span .

Here's jsFiddle: http://jsfiddle.net/leniel/ykg62/2/

+1
source

Replace:

 var finalTotalCount = parseInt(numb) - 1; 

WITH

 var finalTotalCount = parseInt(numb[0]) - 1; 

.match(/\d/g) returns an array of strings matching the regular expression. You want to get the first result of this array, assuming there is only 1 number in your text.

Edit

parseInt seems to use the first element in the array if an array is provided. So technically, my proposal is not required.

+1
source

Change the code this way and try again

 var notification = $("#NewL"); var numb = notification.text().match(/\d/g)[0]; var finalTotalCount = parseInt(numb) - 1; notification.text(notification.text().replace(numb, finalTotalCount )); 

Also in your code:

 <span id="NewL1" visible="false" runat="server"> <span runat="server" id="NewL"></span> </span> 

You have a span inside a hidden span (visible = "false"). Therefore, we will not be able to see any changes. You can simply put your code like this and try again:

 <span runat="server" id="NewL"></span> 
+1
source

All Articles