2014-05-23 40 views
0

我想用隨機數填充所有空數字段。我可以使用隨機數填充所有字段,如下所示。如果輸入字段爲空,請用隨機數填充它

$.each(numberField, function() { 
     x = Math.floor((Math.random() * 10) + 1); 
     ($(this).val(x)); 
    }); 

但是,如果我嘗試它環繞的

if (numberField.val() === "") 

它不工作

我在做什麼錯在這裏? see fiddle

<input type="number" value="0"> 
    <input type="number" value=""> 
    <input type="number" value="4"> 
    <input type="number" value="5"> 
    <input type="number" value=""> 

    var numberField = $('input[type=number]'); 
    var x = ''; 
    if (numberField.val() === "") { 
     $.each(numberField, function() { 
      x = Math.floor((Math.random() * 10) + 1); 
      ($(this).val(x)); 
     }); 
    } 

回答

3

你需要移動你的病情(你正在尋找一個數組是否等於「」,這從來就不是這樣)。您還需要修整值,以檢查它是否真的是空的:

var numberField = $('input[type=number]'); 
var x = ''; 

$.each(numberField, function() { 
    if ($.trim($(this).val()) === "") { 
     x = Math.floor((Math.random() * 10) + 1); 
     ($(this).val(x)); 
    } 
}); 
0

查看updated fiddle

$.each(numberField, function (k, v) { 
    if ($(v).val() === "") { 
    x = Math.floor((Math.random() * 10) + 1); 
    ($(v).val(x)); 
    } 
}); 

看看doc爲jQuery的每個函數。

0

試試這個...

var numberField = $('input[type=number]'); 
var x = ''; 

$.each(numberField, function() { 
    if (this.value === "") { // should check the value inside the loop.. not outside 
     x = Math.floor((Math.random() * 10) + 1); 
     this.value = x; 
    } 
}); 

demo

1

在你的例子numberField是一個數組,所以你的代碼必須是這樣的:

var numberField = $('input[type=number]'); 
var x = ''; 

    $.each(numberField, function() { 
     if ($(this).val() === "") { 
      x = Math.floor((Math.random() * 10) + 1); 
      $(this).val(x); 
     } 
    }); 
0

我認爲這個問題是在這裏:

numberField.val() 

而是使用

$(this).val() 

所以...

var numberField = $('input[type=number]'); 
var x = ''; 
$.each(numberField, function() { 
    alert($(this).val()); 
    if ($(this).val() === ""){ 
     x = Math.floor((Math.random() * 10) + 1); 
     ($(this).val(x)); 
    }; 
}); 

已更新小提琴 http://jsfiddle.net/aaronk85/eC48k/

0

您可以像這樣沒有價值只匹配字段:

$('input[type=number][value=""]').each(function() { 
     this.value=Math.floor((Math.random() * 10) + 1); 
}); 

這裏的demo