tags:

views:

216

answers:

2

Yes, I know it doesn't work in IE and using 'click' works. But here is my problem.

I have two select boxes - Country and City. Selecting a country populates the city select box (and updates a google map).

The following code works like a charm in IE and Opera:

  if (jQuery('#city').length > 0) {
    jQuery('#city').change(function(){ populateCityListBox(); });
  }

If I use 'click' instead of 'change', then the populateCityListBox() is triggered once when I click the select box arrow, and one more time when I click the list box element.

How can I avoid this double triggering?

+2  A: 

The problem is the fact that IE doesn't fire the change event until the element loses focus.

A simple solution might be to keep track of the last value of the select, and only allow the function to execute if it is different.

Also, just a side note, in your change callback, you don't need to wrap it in an anonymous function if all you are doing is calling it.

jQuery('#city').change(populateCityListBox);

works just the same as what you have there.

TM
I have a select that works just fine with .change in IE8 and IE7(Compat) without losing focus.
Marc
Mark: Can you give us the code?
Steven
@Steven, there's no magic $("#id-selector").change(function); as was stated by TM
Marc
@Marc: Sorry, just misread :)@TM: Brilliant. This works like a charm! Thanks!
Steven
A: 

this might work (not tested though):

if ($.browser.msie) {
  var interval = 50;
  var changeHack = 'change-hac';
  var select = $("#viewByOrg");
  select.data(changeHack) = select.val();
  var checkVal=function() {
    var oldVal = select.data(changeHack);
    var newVal = select.val();
    if (oldVal !== newVal) {
      select.data(changeHack, newVal);
      select.trigger('change')
    }
    setTimeout(changeHack, interval);
  }
  setTimeout(changeHack, interval);
}

play with the interval to suite your feelings. also - if the trigger('change') trick won't work, try calling your onchange method there directly

Ken Egozi