如果一切正常,则发出警报

时间:2012-03-04 03:38:30

标签: javascript jquery html

$('input').each(function(){
var id =  $(this).attr('id');
var class =  $(this).attr('class');
var val = $(this).val();

if(val.length == 0){
  alert('Error');
  return false;
}

//HERE STOP UNTIL ALL IS OK

var data = '?id=' + id + '&class=' + class + '&val=' + val;
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});


})

如何制作?我想只在所有输入都有长度>时才使用$ .ajax。 0.

例如,如果我有输入:

1: [aaa]
2: [asad]
3: []
4: [sdfs]

然后

1: - no error and send with ajax
2: - no error and send with ajax
3: - error  and not send with - ajax previous return false
4: - stop script

在这个例子中应该是:

1: - no error - add to array and wait - not send with ajax
2: - no error - add to array and wait - not send with ajax
3: - error stop script - any data not send with ajax.

我想只在所有值都正常的情况下发送ajax。我该怎么做?

1 个答案:

答案 0 :(得分:2)

一个选项是迭代两次,并使用指标/标志变量来跟踪任何验证是否失败:

var valid = true;
$('input').each(function(){
    if($(this).val().length == 0){
      alert('Error');
      valid = false;
      return false;
    }
});

if(valid)
    $('input').each(function(){
        var id =  $(this).attr('id');
        var class =  $(this).attr('class');
        var val = $(this).val();

        var data = '?id=' + id + '&class=' + class + '&val=' + val;
        $.ajax({
          type: 'POST',
          url: url,
          data: data,
          success: success,
          dataType: dataType
        });
    });