views:

592

answers:

1

Hey Guys,

Got the following code:

$(document).ready(function() 
{
   $('a.add-item').click(function()
   {
         if ($(this).parent().find('input').attr('value', '0'))
         {
            $(this).parent().find('input').attr('value', '1')
         }
   });
});

What I would like to do is to create a variable and increment it and then add it to my above code replacing .attr('value', '0')) 0

How would I go about this?

thanks, Keith

+7  A: 

You mean like this:

$(document).ready(function() 
{
   $('a.add-item').click(function()
   {
         var $item = $(this).parent().find('input');
         var value = parseInt($item.attr('value'), 10);
         if (!value) {
             value = 0;
         }
         $item.attr('value', value + 1);
   });
});
Nadia Alramli
You'll need to use parseInt on the value, to prevent concatenation.
Jed Schmidt
You've got the right idea and thanks for replying but when I test the code, it keeps adding 1 as in 1111111 and not incrementing it. cheers,Keith
Keith Donegan
@Jed: Thanks, I fixed it now
Nadia Alramli
@Keith: try it again now
Nadia Alramli
Using parseInt without the second parameter is a hidden bug waiting to happen. It is best to do parseInt(val, 10) to explicitly specify the base.
Paolo Bergantino
Cheers Nadia, it pops up NaN
Keith Donegan
@keith: that was because the input was probably empty at the begining. I added a condition to fix this
Nadia Alramli
@Paolo: thanks for the tip
Nadia Alramli
@Keith, I tested the function in a quick example and it is working as expected.
Nadia Alramli
Thanks a million Nadia, perfect! really appreciate your effort
Keith Donegan
@Nadia, can you explain what this bit: $item.attr('value'), 10) - What does the 10 mean?
Keith Donegan
it's part of the parseInt( string, base) method. the 10 is the base i.e. decimal, and the string is the parent input's value
Russ Cam
@keith: the 10 in parseInt($item.attr('value'), 10) is for specifying the int base. Without it a string that starts with "0" can be interpreted as an octal. See this for more details http://www.w3schools.com/jsref/jsref_parseInt.asp
Nadia Alramli