Jquery unselect event input element?

Possible duplicate:
Deselect what was selected on the tab with .select ()

Is there any way to detect when the user does not select the text in the input element through jQuery?

I do

$('#input').select(function () {...}

to show a toolbar with formatting options when the user selects the text, but I could not figure out how to determine if the user clears the selection.

Any suggestions?

+4
source share
3 answers

Try Blur Event

 $('#input').on('blur',function () { if( this.value == ''){ alert('Blur Event - Text box Empty'); //Your code here } }); 

This fires as soon as the input field loses focus. ie; he was not selected.

+3
source

So, after some experimentation, I solve the solution. Here is what I did. I created a function that returned the selected text from the document:

 function getSelectedText() { return document.selection.createRangeCollection()[0].text; } 

From here, I was able to adapt the CupOfTea696 solution to use jQuery to bind events like this:

 $("#input").on("click change keyup select", function (event) { if(getSelectedText().length < 1) hideAppBar(); else showAppBar(); }); 

So, I basically check the length of the selected text and based on this show or hide the context menu.

I still have a blur problem, but this is more likely due to the click event fired in AppBar rather than the above solution. I also tested this only on Win8, so I’m not sure if this will be a valid web solution, but I don’t understand why this will not work.

+3
source

There is no real javascript event to detect this. The best solution here is to check for both blur and focus, keystrokes, and the mousedown event. This would be the most complete solution, although it was not perfect. You can bind it to the whole event at the same time using the .on method.

 $("#input").select(function() { //do something here }); $("#input").on("blur focus keydown mousedown", function() { //do something else here });​ 

Again, this is not a complete solution, since a blur event can occur without clearing the selection. But this is the best you can do.

+1
source

Source: https://habr.com/ru/post/1437693/


All Articles