2011-08-25 62 views
0

我有一些輸入文字是這樣的:jQuery的 - 檢查輸入值的文本

<input type="text" value="5" maxlength="12" id="qty" class="input-text qty" name="qty2050" tabindex="1"> 

and 

<input type="text" value="0" maxlength="12" id="qty" class="input-text qty" name="qty2042" tabindex="1"> 

而且我想用jQuery檢查每個輸入值,以執行一個功能,如果有來自不同數量0在一個輸入。

編輯 我在unlod之前如何在頁面上做到這一點?

感謝您的幫助。

+0

你有什麼要觸發它進行檢查?頁面加載/點擊/更改 – Ben

+0

我想檢查它是否正在加載,謝謝 – Bizboss

+0

到目前爲止您嘗試了什麼? jQuery有很好的文檔:http://api.jquery.com/ –

回答

2

嘗試在此way-

$(window).unload(function() { 
    $('.input-text qty').each(function(){ 
     var val = parseInt($(this).val(),10); 
     // you can use math.floor if your input value is float- 
     //var val = Math.floor($(this).val()); 
     if(val !== 0) 
     alert(val); 
    }); 
}); 
+0

如果您使用嚴格比較,則必須先將該值轉換爲數字。 '.val()'總是返回一個字符串。 –

+0

如果你能寫這個'if(this.value){'沒有jquery –

+0

@ Felix Kling-感謝你的建議,更新了答案。 – Vivek

0

使用變化():http://api.jquery.com/change/

例:有效性試驗添加到所有的文本輸入元素:

$("input[type='text']").change(function() { 
    // check input ($(this).val()) for validity here 
}); 
1

你不應該有一個頁面上有兩個相同的ID。 很簡單的應該是:

$('input.input-text.qty').each(function(){ 
    if ($(this).val() !== '0') { 
    alert('Gotcha!'); 
    return false; //quit loop since we're ok with 1 occurance 
    } 
}); 
1
$('.input-text').change(function() { 
    if($(this.val() != "0")){ // 
     action here 
    } 
}); 
+0

如果您會收到錯誤檢查括號 –

0
var checkInput = function() { 
    if(this.value !== '0') { 
     // do something 
    } 
} 

$(window).bind('unload', checkInput); 
$('input[type=text]').change(checkInput); 

我希望這有助於。

0

如果你真的想這樣的卸載事件事遂所願,這將工作(其未經測試),否則綁定到任何你想要的事件:

$(window).unload(function() { 
    $('.input-text qty').each(function(){ 
     if($(this).val() !== '0') {  
      alert("there is a 0"); 
      return false;//breaks out of the each loop, if this line present will only get one alert even if both fields contain 0 
     } 
    }); 
    });