Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a read only jQuery date picker textbox?

We have a JQuery date picker control on a read only text box. We make the textbox read only so users can't enter their own dates. This works great but we want to provide the users the option to clear out the contents of the text box after they have selected a date.

How can you do this? Apparently this functionality used to be built into the control but was removed.

Note: we disable input into the textbox using:

$("#text-box").keypress(function (e)
{
    e.preventDefault();
});

Update: I solved this with a slight variation of the selected answer:

    myTextBox.keydown(function(e){
        if (e.keyCode == 46 || e.keyCode == 8) {
            //Delete and backspace clear text 
            $(this).val(''); //Clear text
            $(this).datepicker("hide"); //Hide the datepicker calendar if displayed
            $(this).blur(); //aka "unfocus"
        }

        //Prevent user from manually entering in a date - have to use the datepicker box
        e.preventDefault();
    });
like image 834
Marcus Leon Avatar asked Dec 16 '10 19:12

Marcus Leon


People also ask

How do you make a Datepicker not editable?

$("#my_txtbox"). attr( 'readOnly' , 'true' );

How do I make Datepicker textbox editable?

1 Answer. Show activity on this post. $('#start_date'). datetimepicker({timeFormat: "HH:mm:ss", dateFormat:"dd-mm-yy", constrainInput: false, maxDate: maxdate});

How to make datepicker readOnly?

$("#datepicker"). attr('readonly', 'readonly');

How do I remove date picker?

To destroy a datepicker in jQuery UI, we will be using destroy() method. jQuery UI destroy() method is used to remove the complete functionality of the datepicker().


1 Answers

How about excluding keys thats user use to clear textbox like 'del', 'backspace' etc.?

$("#text-box").keypress(function (e)
{
  switch(e.keyCode) { 
          case 46:  // delete
          case 8:  // backspace
            break;
          default:
            e.preventDefault();
            break;
       }
});
like image 162
Andrew Orsich Avatar answered Oct 11 '22 04:10

Andrew Orsich