Joshua Robison
Joshua Robison

Reputation: 1881

how to preform subtraction on a string

Aside from inserting illegal attributes into an tag and invalidating my HTML, I've never done what I am trying to do before and will most likely benefit from this answer in other areas of my work.

I think the problem is I am trying to subtract "1" from a string "$(this).attr('num')"

This might work if I first convert "$(this).attr('num')" into an integer and then subtract "1" from it.

I am open to any other solutions. Thanks

//

$("#jumpPreviousButton").click(function(){
var imageNumber = $(this).attr('num'); 
  $("#bgImageBox").css({
    "background-image": "url(/galleryImages/worksImage"
    + imageNumber - 1

    +".jpg)"
  }).attr('num', imageNumber - 1);

  return false;}
);

//

Upvotes: 1

Views: 2755

Answers (5)

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

use parseInt but don't use parseInt without a radix

The parseInt() function parses a string and returns an integer.

The signature is parseInt(string, radix)

so the answer to your question is:

  var imageNumber = parseInt($(this).attr('num'), 10);

The second argument forces parseInt to use a base ten numbering system.

  • The default input type for ParseInt() is decimal (base 10).
  • If the number begins in "0", it is assumed to be octal (base 8).
  • If it begins in "0x", it is assumed to be hexadecimal

why? if $(this).attr('num') would be "08" parsInt without a radix would become 0

Upvotes: 4

Aly
Aly

Reputation: 16265

Why dont you use jquery's data() function instead of attr() to add the num field to your tag.

  1. Jquery's data will not invalidate your markup
  2. You can add any data type in data, so there is no need to use parseInt

For example: HTML:

<html>
    <body>
        <p>hello</p>  
    </body>
</html>

JS:

$('p').data('foo',52);
var val = $('p').data('foo');
alert(val);
$('p').data('foo', val + 1);
alert($('p').data('foo'));

This will alert 52 and then 53. You can see a demo here.

Upvotes: 4

Marek Tuchalski
Marek Tuchalski

Reputation: 489

parseInt() function is your friend ;)

var imageNumber = parseInt($(this).attr('num')); 

Upvotes: 3

GolezTrol
GolezTrol

Reputation: 116110

As you say, converting it to integer first will help. Use the parseInt() function for that. :) (Or parseFloat() if it is a floating point number.)

Upvotes: 5

meze
meze

Reputation: 15087

(parseInt(imageNumber) - 1)

if the number is an integer.

Upvotes: 3

Related Questions