Karem
Karem

Reputation: 18103

Change to an option in a select with jQuery

As the title says how can i change to an option with value xx in a select?

I can do $('#qty').val(2); that works, but I want it to trigger the change() function.

http://jsfiddle.net/Kc3ES/

So at the document ready it should also alert "Works!" since it just got changed.

How can i do this?

Upvotes: 0

Views: 128

Answers (3)

Mutation Person
Mutation Person

Reputation: 30498

The following should work:

 $('#qty').val(2).change();

Although, you might want to consider adding an extension to do it in one for you:

$.fn.valchange = function(x){
    this.val(x).change();
} 

$('#qty').valchange(2);

http://jsfiddle.net/Kc3ES/2/

Upvotes: 0

fin1te
fin1te

Reputation: 4351

You can chain the trigger method after the call to val.

$(document).ready(function() {
   $('#qty').val(2).trigger('change');
});​

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

you should do

 $('#qty').val(2).trigger("change");

http://jsfiddle.net/Kc3ES/1/

Upvotes: 1

Related Questions