0

I use 2 same inputs at search form. I want to control data typing. For example, user enter time or price in any interval. Second value must be larger than first. How to make user can not enter larger value to second field?

For date:

@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" } )

and for price:

@Html.TextBox( "price1", string.Empty, new { @class = "priceClass" } )
@Html.TextBox( "price2", string.Empty, new { @class = "priceClass" } )

date1 and date2 are string, price1 and price2 are double. Sorry for my bad english..

4

1 回答 1

1

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)

于 2012-08-17T10:00:31.237 回答