2012-08-17 51 views
0

我在搜索表單中使用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" }) 

日期1date2的是字符串,價格1price2是雙。對不起,我的英文不好..

+0

這看起來像ASP.NET MVC。你有沒有考慮過使用驗證器?你可以寫一個自定義的驗證器屬性,然後用它裝飾你的視圖模型屬性。 – 2012-08-17 09:28:53

+0

但是,我不使用任何模型。產品具有日期和價格屬性。我發送參數到這個Action方法: public ActionResult Search(string date1,string date2,double?price1,double?price2){} – 2012-08-17 09:37:50

+0

這就是你的問題:你應該使用視圖模型。 – 2012-08-17 09:38:14

回答

1

您需要調整這個所以它匹配無論你的後端代碼是返回回

這裏,您有幾種選擇,你可以驗證,當用戶提交表單或當用戶停止輸入。在提交相當直接

if ($('#second').val() > $('#first').val()){ 
     return false; 
    } 

對於比較日期,check this out

或者當用戶停止輸入,你可以做到這一點,得益於this great answer你可以做到這一點

$(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 
    } 
    } 
}); 

而且,datepickers ,如果您使用的是jQuery UI datepicker,則可以選擇指定禁用某些日期範圍,因此您可以使用該選項禁用比第一個日期選擇器的值更早的任何內容(但所有這一切只是客戶端檢查,我f這對您的應用程序至關重要,您將不得不在C#或任何您使用的語言中執行後端檢查)