Ignoring Input to a Text Field with jQuery

The other day I was trying to use an input field for display only: the user would select couple of elements from an overlay box and, once their selection was completed, be presented with a generated output in the input field. This should be for overview purposes only and the user should not be able to type manually into the field; a scenario much like the one covered by the jQuery Datepicker. My first reflex of setting the fields disabled attribute unfortunately did not work well since inputs with disabled=”disabled” will not only drop the onClick event but, even worse, be ignored for the submission of the surrounding form. However, it turns out that there is a jQuery one-liner for the problem:

[code lang=”javascript”]
$(‘#month_range’).keypress(function(event){event.preventDefault();});
[/code]

This will essentially ignore any key events on the month_range input field. Be aware though that it will as always just protect the user a bit from themselves and not in any way relieve you from validating the input (just try to c&p something into the field…).