开发者

Need help with a JavaScript function to determine ascending numbers

I have table rows, which have a start number and an end number (input fields).

Per row, the end must be larger than the start.

From inputs left to right, top to bottom the numbers must be larger than the last.

So there are 2 inputs per row, and 4 (for example) rows. Each number is bigger than the last.

I've been trying to validate this using this function

   var maxDepth = 0,
  didValidate = true;

// I assume this reads from left to right top to bottom as they are that way in the markup
$('.input-start-depth, .input-end-depth').each(function(i) {

  maxDepth = Math.max(maxDepth, parseFloat($(this).val(), 10));

  var isStart = ($(this).hasClass('input-start-depth'));
  var value = $(this).val();


  if (isStart && value > maxDepth) {
    didValidate = false;

    return false;
  };

  lastValue = value;

});

I've been racking my head to get this to work. The other important thing is the number of rows is dynamic, there could be 1 or 10,000 or any in between.

Basically it is meant to say if the start depth is larger than the max depth so far, it should fail.

But it is validating numbers when they shouldn't be valid.

What am I doing wrong?

开发者_StackOverflow中文版Cheers.


i don't think you can assume the order in which the elements are read. you should look into reading the table row by row. here's some code to look at to see what i mean:

$('table#mytable tr').each(function() {
  var start = parseInt($(this).find('.input-start-length').val());
  var end   = parseInt($(this).find('.input-end-length').val());
  if(start > maxDepth) {
    didValidate = false;
    return false;
  }
  lastvalue = start;
});


I ended up using, which seems to work

$('table tbody tr').each(function(i) {


                var startDepth = parseFloat($(this).find('.input-start-depth').val(), 10);
                var endDepth = parseFloat($(this).find('.input-end-depth').val(), 10);


                var anyNans = isNaN(startDepth) || isNaN(endDepth);

                if (anyNans || startDepth > endDepth || startDepth < maxDepth) {
                    didValidate = false;
                    return false;
                };
                maxDepth = Math.max(maxDepth, endDepth);

            });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜