3

I have

<input type="text" id="first"> 

and have

 $('#first').select();

So, in some case I want to deselect the input, something like

$('#first').deselect();

Can you provide the code how to deselect selected input? But that is not focus, I am not talking about selecting input itself, but selecting the text in it. Like you double click on text. Thanks.

KoboldMines
  • 428
  • 2
  • 6
  • 21

3 Answers3

6

Based on jQuerys API documentation, .select() is simply a helper function that performs focusing and selection of the text node:

In addition, the default select action on the field will be fired, so the entire text field will be selected.

So, if you want the opposite, calling .blur() will have the opposite effect. It will defocus from the field and also reset the selection. See proof-of-concept below:

$('#select').on('click', function() {
  $('#first').select();
});

$('#deselect').on('click', function() {
  $('#first').blur();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="first" value="Lorem ipsum">
<button type="button" id="select">Select</button>
<button type="button" id="deselect">Deselect</button>
Terry
  • 63,248
  • 15
  • 96
  • 118
1

You can use:

$('input').blur();
1

You can simply use two methods

input.blur();
input.selectionStart = input.selectionEnd;

let input = document.querySelector("input");

const select = ()=> {
  input.select();
}

const unSelect = ()=> {
  // Using blur()
  // input.blur();
  
  // or using this
   input.selectionStart = input.selectionEnd;
}
<input type="text" value="Select or unselect input value">
<button onclick="select()">Select Text</button>
<button onclick="unSelect()">UnSelect Text</button>
Abdul Rehman
  • 139
  • 1
  • 5