0

我在我的 js 文件中做:

var aryYears= [];
    $(".year").each(function(){
        aryYears.push($(this).val());
    })

所以我可以在 saveChanges 函数中发送一个年份数组作为参数。

我需要字段年份。如果数组的每一年都有一个值,我如何检查上面的代码?如果年份为空,如何触发警报或对话框?

万分感谢!!

4

5 回答 5

0

我建议:

var aryYears= [];
    $(".year").each(function(){
        var v = $(this).val();
        aryYears.push(v !== '' ? v : prompt('Please enter a year:'));
    })

JS 小提琴演示

更新(一段时间后,由于几个意外的无限循环,叹息......):

function getValue(v, hint) {
    if (v && v !== '') {
        return v;
    } else {
        v = prompt('Please enter a ' + hint + ': ');
        return getValue(v);
    }
}

var aryYears = [];
$(".year").each(function () {
    var v = $(this).val();
    aryYears.push(getValue(v, 'year'));
})
console.log(aryYears);

JS 小提琴演示

如果没有别的,后一个示例应该让用户处于一个他/她感到沮丧到足以输入一个值的位置,但是没有对该值进行完整性检查;所以请记住验证用户输入。

还有一个更有用的版本,它突出显示input您要求的值,并为其添加input

function getValue(v, hint) {
    if (v && v.trim() !== '') {
        return v;
    } else {
        v = prompt('Please enter a ' + hint + ': ');
        return getValue(v, hint);
    }
}

var aryYears = [];
$(".year").each(function () {
    var self = $(this),
        v = $(this).val();
    if (!v || v === '') {
        self.addClass('invalid');
    }
    v = getValue(v, 'year');
    aryYears.push(v);
    self.removeClass('invalid').val(v);
})
console.log(aryYears);

JS 小提琴演示

于 2013-06-12T11:28:47.940 回答
0

尝试这样检查数组是否为空

 $(".year").each(function(){
   var val =  $(this).val();
   if(val)
     aryYears.push($(this).val());
   else
     alert('null/ empty');
})

演示

于 2013-06-12T11:29:38.620 回答
0

你的意思是这样的吗?

var aryYears= [];
$(".year").each(function(){
    if($(this).val() == "") {
        alert("The value of .year is empty");
    } else {
        aryYears.push($(this).val());
    }
});
于 2013-06-12T11:30:21.427 回答
0
var aryYears = $(".year").map(function(){
        if(this.value !== "")
         return this.value;
    }).get();

if(aryYears.length < $('.year').length){
  alert("please enter all values");
}
于 2013-06-12T11:31:13.780 回答
0

你可以试试这个。

$('.something').each(function() {
    var checkValue = $(this).val();
    checkValue = $.trim(checkValue);
    if (Math.floor(checkValue) == checkValue && $.isNumeric(checkValue)) {
       if (checkValue == "") {
            alert('not value'); 
      }
    }
});
于 2013-06-12T11:32:00.873 回答