2014-10-08 59 views
1

我在一個形成若干類型的輸入已實施,最高指定分鐘:如何檢查一個數字類型輸入唱歌JavaScript的有效性?

<input class="qty_input" name="quantit" type="number" value="5" min="1" max="50" maxlength="2" style="width:4em;"></input> 

輸入類型作品數量:如果再進入別的一些,或者如果數值不在規定範圍內,輸入變爲紅色。

我有一個javascript函數提交輸入更改窗體。

<script type="text/javascript"> 
(function($) { 

    function doAjax() { 
    $.ajax({ 
     url : "blabla", 
     type: "POST", 
     data : $("#form-configurator").serializeArray(), 
     dataType: 'json', 
     success: function(data) 
     { 
      console.log(data); 
     }, 
     error: function() 
     { 

     } 
    }); 
    } 
$('input[type=number]').change(function() { 

    // test Validity 

    doAjax(); 
    }); 
})(jQuery); 
</script> 

我想測試之前運行doAjax()函數,如果數字輸入有效。

有沒有一種簡單的方法來做到這一點,比如測試數字類型輸入的「有效」參數? (它應該存在的輸入進行一些測試本身...)

感謝你的幫助,

亞歷

+0

'isNaN()'派上用場,以檢查其是否號碼或不 – Navin 2014-10-08 09:41:26

+0

你能評價答案? – 2014-10-08 11:23:23

回答

1

可以使用isNaN()功能驗證輸入是一個數字或沒有。您可以添加其他條件,如果像

if(isNaN(value) || value <1 || value > 50) 
return ; 
else 
    your logic  

如果該值不是number.If它是數字,它將返回true,那麼它將返回false。

here

+0

這將起作用,但如果驗證規則不在HTML和JS中重複,那將會更好。 – 2014-10-08 09:50:16

+0

@AdamHarwood現在檢查它 – PSR 2014-10-08 09:54:42

+0

這是想法。使用type = number,isNaN和min/max檢查已經由html執行。沒有辦法在JS中檢查此測試的結果,而不是再次進行所有測試? – Alexglvr 2014-10-08 10:24:39

0

這裏活樣本:http://jsfiddle.net/zueku6mo/

$('input[type=number]').change(function() { 
    var min = $(this).attr("min") * 1; 
    var max = $(this).attr("max") * 1; 
    var val = $(this).val().length ? $(this).val() * 1 : NaN; 
    // test Validity 
    if (val >= min && val <= max) { 
     $(this).css("background-color", "white"); 
     doAjax(); 
    } else { 
     $(this).css("background-color", "red"); 
    } 
}); 
  • 投分鐘& max屬性與* 1
  • 到號碼檢索當前值和投它如果不爲空
  • 怎樣數
  • 做一些數學失敗,如果有NaN VA略
  • 設置背景的紅色信號值誤差
相關問題