Why is $ (": select") the focus not working, but $ (": input"). Does the focus work?

I have jQuery code that does something when input or select elements get focus. Although my code for the input element works, the select element does not work.

That's what I'm doing.

<body> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(":input").focus(function () { //this works //do something }); $(":select").focus(function () { //this doesn't //do something }); }); </script> </body> 

I tried several choices, for example, using $ ("select") instead of $ (": select"), but it doesn’t work.

I am starting to work with jQuery.

I appreciate if you could tell me how I can make it work.

Thanks a lot!

+4
source share
4 answers

In short and simple: because :select does not exist.

$('select') will work , but only if there is a <select> element in your code. You did not specify above in your code.

See the list of selectors .

:input exists instead :

Selects all input elements, textarea, select, and button.


In general: Selectors starting with a colon : are pseudo-selectors. They are defined by jQuery (they are not valid CSS selectors) and select elements with a specific state or property).

You have already encountered :input . He selects all form controls. Another is, for example : visible , which selects all displayed (visible) elements.


Update:

<select> elements must exist when $('select').focus(... is executed. I don’t know what software you use, but if they load elements, for example through Ajax, then most likely they still do not exist when your code is executed.

  • Make sure the page has <select> elements.
  • You may need to use .live() :

     $('select').live('focus', function() { //stuff }); 
+6
source

There is no choice: select select, but since "select" is its own tag in HTML, you can simply use $ ('select') (for example, you can use $ ('body'), for example). A better approach is probably to assign an "id" to your "select" element and then use $ ('# id') to directly select that element.

+1
source

$ (": select") is not a valid selector. http://api.jquery.com/category/selectors/

0
source

You should avoid using: input: select alone. This is a performance killer, especially if you have elements in the DOM .: input tools. jQuery must look for all the elements in the DOM to search for input. Below the selector stands out faster and more efficiently.

$ ('# MyForm'). Find ('input')

Check performance test (75% faster) http://jsperf.com/input-selector-performance0

So you can basically do

 $('#myform').delegate('select','focus', function() { // what ever you want to do here }); 
0
source

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


All Articles