Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind click event on select option

Tags:

jquery

I've got a problem making a click event on an HTML option element work.

Even a simple console.log('hello!'); won't work.

I am trying with this:

$('#mySelect option').bind('click', function(){
  console.log('hi!');
});

It worked for a while, but then stopped.

like image 435
Salvatore Dibenedetto Avatar asked Sep 05 '12 05:09

Salvatore Dibenedetto


People also ask

How to bind a click event in jQuery?

Use the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

How to bind event explain with example?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements. data: This is the data which can be shown over the selected elements.

How to bind an event in JavaScript?

Users can follow the below syntax to handle bind an event using addEventListener in JavaScript. element. addEventListener(event, eventHandler, useCapture); In the above syntax, we have passed the event and eventHandler callback function as a parameter of the addEventListener method.

How do we bind events to elements using jQuery?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs. For more flexible event binding, see the discussion of event delegation in .


3 Answers

In my case following code works

$('#myItem').change(function(){
            //do somthing
})
like image 58
Mohsin Saeed Avatar answered Sep 24 '22 16:09

Mohsin Saeed


You can bind using .on() by giving <select> id. In general, change is the event called upon <select>.

So, there is no need to mention option while binding event.

$(document).on('change','#mySelect', function(){<br>
    console.log('hi!');
});

OR

$('#mySelect').bind('change',function(){<br>
    console.log('hi!');
});
like image 26
Prem Avatar answered Sep 25 '22 16:09

Prem


This solve the case - for my needs (to catch the event when some of the select element on my page is clicked). Have not validated touch behavior though but Firefox, Chrome seems to be OK w/ this

$('.class_for_select').focus(function() {
    // do something here
});
like image 21
user3472193 Avatar answered Sep 23 '22 16:09

user3472193