views:

41

answers:

1

I have a spurious problem which seems to indicate the index value got from the jquery each method does not always start at 0.

My javascript looks a bit like this:

$("#mylist").each(function(index) {
    var obj = new myclass();
    obj.property = "whatever";
    obj.sequence = index + 1;
    parentobj.list.push(obj);
});

This all gets packaged into json and ajaxed (please pardon verb usage) back to the server. The server then deserialises the json into .net objects. It's at this point I get an error:

The value '91111' cannot be parsed as the type 'Int16'. 

This is at the point it tries to push the sequence value into a short field.

I cannot recreate this (always happens to other users). I may be able to add some debug code to the javascript files in question during a quiet period but there's no guarantee it will happen then.

There also seems to be a strange pattern to the values. The values in the log are: 61111, 81111, 91111, 111111, 211111, 311111. These neither ascend or descend and sometimes repeat.

Can anyone shed a light on this or confirm that I cannot trust the index to start from zero?

Thanks

+2  A: 

As quoted from the jquery API on .each():

Each time the callback runs, it is passed the current loop iteration, beginning from 0

I am assuming, therefore, that it is always indexed at 0. I have had strange problems with jQuery treating an operation of an int + 1 as a string concatenation (which could explain the digit followed by trailing ones in your errors). For example, look at the following code:

var a = 1;
var b = a + 1;

With code similar to this, I would get 11. The solution is to wrap a in a parseInt(), like this:

var a = 1;
var b =  parseInt(a) + 1;

Try modifying your code to the following and see what happens:

$("#mylist").each(function(index) {
    var obj = new myclass();
    obj.property = "whatever";
    obj.sequence = parseInt(index) + 1;
    parentobj.list.push(obj);
});
nsw1475
you can simply use ++ i instead of i++ , ++i should work
gov
@gov - if you're suggesting using "sequence = ++index", then that would have the side affect of incrementing the index value
Chris Simpson