我在搜索表单上使用了2个相同的输入。如果我想控制数据类型,例如,用户以任意间隔输入时间或价格的话,那么第二个值必须大于第一个。 那么,如何使用户不能在第二字段中输入较大的值? 数据代码:
@Html.TextBox( "date1", string.Empty, new { @class = "dateClass", type_datepicker = "true", @id = "datepicker" } )
@Html.TextBox( "date2", string.Empty, new { @class = "dateClass", type_datepicker = "true", @id = "datepicker2" } )
价格代码:
@Html.TextBox( "price1", string.Empty, new { @class = "priceClass" } )
@Html.TextBox( "price2", string.Empty, new { @class = "priceClass" } )
date1和 date2 是字符串, price1和 price2 是双精度的。/p>
You need to tweak this so it matches whatever your backend code is returning back
You have a few options here, you can either validate when the user submits the form or when the user stops typing. At submit is pretty straight forward
if ($('#second').val() > $('#first').val()){
return false;
}
For comparing dates, check this out
Or you can do it when user stops typing, thanks to this great answer you can do this
$(document).ready(function(){
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 second for example
//on keyup, start the countdown
$('#second').keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#second').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
if ($('#second').val() > $('#first').val()){
alert('cannot do that'); //take whatever action you need here
}
}
});
Also, for datepickers, if you are using jQuery UI datepicker, there is an option to specify disabling certain date ranges, so you can use that to disable anything earlier than the value of the first datepicker (but again all that is just client side checks, if this is crucial to your application you will have to do back-end checks as well in C# or whatever language you are using)