[英]Input value jQuery check length and value?
在驗證輸入的值時,我仍然被困在這里。 如果值在0.4
和0.9
之間,輸入n2
將刪除只讀。 另一方面,如果值小於0.4
或大於0.9
,它將顯示模態對話框。 我的問題是如果用戶輸入的值鍵不是十進制值,則驗證值/長度? 假設用戶插入值 1,那么我的 jquery 不會觸發,因為我的長度>=3
.. 如果我把長度檢查> 1
,那么當用戶鍵入十進制值例如0.5
時,模態對話框將彈出3 次.. 因為我的長度值>= 3
.. 如果我刪除長度檢查,只要用戶鍵入超過 1 的值長度,它就會一直彈出模式對話框。 我的問題是如果有效范圍值在0.4
到0.9
之間,如何控制這種情況,同時也可以檢查不是十進制數的值? 可能嗎?
<input type="text" class="form-control input-sm da" name="da" id="da" value="" autocomplete="off" />
<div class="form-group actionDiv" style="display:none">
<label for="cdaaction">Action </label>
<input type="text" class="form-control input-sm cdaaction" name="cdaaction" id="cdaaction" value="" />
</div>
<input type="text" class="form-control input-sm n2" name="n2" id="n2" value="" autocomplete="off" readonly />
$(document).ready(function() {
$(".da").keyup(function() {
var dInput = $(this).val();
if ($('.da').val().length >= 3)
{
if(dInput < 0.4 || dInput > 0.9)
{
var mymodal = $('#mi-modal');
mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +' ?');
mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
$("#mi-modal").modal('show');
$("#modal-btn-si").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').show();
});
$("#modal-btn-no").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').hide();
$("#da").focus();
});
$(".n2").attr('readonly', true);
}
else
{
$(".n2").removeAttr("readonly");
$('.actionDiv').hide();
}
}
});
});
使用parseFloat()
$(document).ready(function() {
$(".da").keyup(function() {
//var dInput = $(this).val();
var val = parseFloat($(this).val());
if (!isNaN(val) && (val < 0.4 || val > 0.9))
//if(dInput < 0.4 || dInput > 0.9)
{
var mymodal = $('#mi-modal');
mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +' ?');
mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
$("#mi-modal").modal('show');
$("#modal-btn-si").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').show();
});
$("#modal-btn-no").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').hide();
$("#da").focus();
});
$(".n2").attr('readonly', true);
}
else
{
$(".n2").removeAttr("readonly");
$('.actionDiv').hide();
}
}
});
});
您可以考慮在blur()
上觸發您的代碼。 當用戶將焦點移出輸入框時,可以檢查輸入的值是否正確。
此外,Carsten 所說的是正確的:使用type=number
作為輸入,您不需要檢查輸入長度,只需要檢查值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.