Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deselect contents of a textbox with javascript

I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):

$("#txt1").select();

Is there a way to do the opposite? To deselect the content of a textbox? I have the focus event of a series of textboxes set to select the contents within them. There are times now that I want to focus a particular textbox WITHOUT selecting it. What I am planning on doing is calling the focus event for this particular textbox, but then follow it with a call to deselect it.

$("input[type=text]").focus(function() {
    $(this).select();
});

//code....

$("#txt1").focus();

//some code here to deselect the contents of this textbox

Any ideas?

Thanks!

like image 862
Dan Appleyard Avatar asked Apr 27 '09 18:04

Dan Appleyard


People also ask

How do you deselect an element?

Press Esc. Click with any tool (including the Arrow) on an empty part of the project to deselect all the selected elements at once. Click a selected element while holding down the Shift key.

What is select() in JavaScript?

select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.


2 Answers

what about this:

$("input").focus(function(){
  this.selectionStart = this.selectionEnd = -1;
});
like image 101
mkoryak Avatar answered Sep 30 '22 15:09

mkoryak


If you just assign the value of the textbox to itself, it should deselect the text.

like image 27
Brandon Avatar answered Sep 30 '22 15:09

Brandon