views:

111

answers:

4

Here's what I want to do. I want to trigger an event every time a select element changes. I have a multiline select and when I make changes (click on elements), it does not change until the select box loses focus. So I'm trying to force a blur every time the select box is clicked. That way if it changes, it will trigger the changed event. If it doesn't change, nothing will happen.

How do I do this? Am I even approaching this the right way? Jquery answers are okay as well.

+1  A: 

You could attach an onclick handler to the select and the individual options. basically onclick="this.blur();". I've always found that click events on <select> elements to be a pain, as nothing happens at the point you expect it to.

Marc B
+3  A: 

Using jQuery do:

$('#mySelectBox').change(function() {
   //do things here
});

According to the documentation at http://api.jquery.com/change/, the event is triggered immediately when the user makes a selection.

Check out this demo to verify that this works: http://jsfiddle.net/AHM8j/

Ender
Yes. This is the event the OP should be listening for.
Matt Ball
This might not happen in IE. IE is notoriously bad with the `change` event. http://stackoverflow.com/questions/1637503/jquery-change-event-on-select-not-firing-in-ie
Jeff Rupert
That demo I provided seems to me to be working in IEs 6-8. Additionally, from the documentation provided: "As of jQuery 1.4 the change event now bubbles, and works identically to all other browsers, in Internet Explorer."
Ender
That's what I thought. What's super frustrating is that when I copy and paste my code into that demo site, it works as expected. But when I run it within my application, it doesn't. Maybe it has something to do with Microsoft's AJAX libraries. I more/less inherited this code and so there's a number of extra unused javascript libraries being referenced.
Jason Thompson
Try using jQuery.noConflict() and then (for the sake of convenience) wrap your jQuery in this: (function($) { // $() will work as an alias for jQuery() inside of this function})(jQuery); I can't guarantee that will fix your problem, but it can't hurt.
Ender
A: 

In addition to Ender the full code could be somthing like this.

$('#mySelectBox').change(function() {
    $('#thingToBlur').blur();
})

Reference: http://api.jquery.com/blur/

Muffun
+1  A: 

Okay, Here's what was going on. I was including the -vsdoc version of JQuery instead of the actual JQuery library. This also fixes some issues I was having with some plugins such as blockUI.

Jason Thompson
To clarify, you do NOT want to include the -vsdoc. This should be used for intellisense only.
Jason Thompson