Mike Crittenden
Mike Crittenden

Reputation: 5917

Select a <select> option using jQuery in a way that triggers any change handlers

I'm using Google Translate's dropdown menu to translate a site, but this doesn't persist across pages, so I'm trying to manually select the needed option on page load to make it persistent.

However, just using $('#google_translate_element select').val('es'); doesn't trigger the event that actually translates the page. I can't figure out how to manipulate this programmatically in a way that actually triggers the onchange event.

I've also tried:

$('#google_translate_element select option[value=es]').attr('selected', 'selected').trigger('change');

and

$('#google_translate_element select').val('es').trigger('change');

No luck. Any ideas?

For the record, here's the HTML I'm working with (which is output by Google Translate's script)

<div id="google_translate_element">
  <div class="skiptranslate goog-te-gadget" style="">
    <div id=":1.targetLanguage" style="display: inline; ">
      <select class="goog-te-combo">
        <option value="">Select Language
        </option>
        <option value="es">Spanish
        </option>
      </select>
    </div>
  </div>
</div>

Upvotes: 1

Views: 4300

Answers (3)

Mike Crittenden
Mike Crittenden

Reputation: 5917

I found http://translateth.is/ and ended up using that instead of this nonsense. It persists across page loads by default and still uses Google Translate's API.

Upvotes: 2

nobitavn94
nobitavn94

Reputation: 327

Try this: $('#google_translate_element select').bind('change', function(){alert('changed');}); That registers handler for onchange event.

Upvotes: 0

farinspace
farinspace

Reputation: 8801

Your code works fine for me ... code it be that the event is not "change" but rather "click".

Upvotes: 0

Related Questions