开发者

Select trigger event not working in jQuery

I have the following function:

jQuery("el").click(function() {

    var index = jQuery(this).index(),
    select = jQuery('select.SelectClass option').get(index + 1),
    $select = jQuery(select);
    $select.attr('selected', 'selected');
    jQuery(jQuery('select.selectClass').get(0)).trigger('change');   

});      

I am attempting to trigger the change event on the select and i开发者_StackOverflow社区t seems this is not working. Another thing to note is there is also prototype code used on this page that effects these selects. There are other elements on the page that are effected by the change event on the page.

Is there any issues with this code? Or does anyone have a recommendation to trigger this event?


it doesn't present any problem, but the execution status depends on the html as well. Maby you should post some html sample as well.
As for the js, it can be improved : use the $(selector).eq(i) method instead of $($(selector).get(i)).
this is the function that should trigger the change event on the first 'select.selectClass' item:

function triggerChange() {
    var index = jQuery(this).index(),
    $select = jQuery('select.SelectClass option').eq(index + 1);  
    $select.attr('selected', 'selected');
    jQuery('select.selectClass:first').trigger('change');   
}

now it depends on you when you call it.You can bind it to be triggered when you click an element : jQuery(element).click(triggerChange);.


I think your issue is easily solved by binding the change event to a common function and then just call that function normally in whatever context you want.

$('#foo').change(fred);
$('#bar').change(fred);

function fred(e) {
//do stuff
}

...

function someotherstuff() {
    fred(); //fires same behavior as the change event.
}


This jQuery("el").click(function() { won't trigger any events. If you have an element set to a variable named el you need to use jQuery(el).click(function(){. If your intent is to set up an event handler for when the select option changes use: jQuery("#yourSelectsIDHere").change(function(){ /* do your event stuff here */});. To trigger the change event use jQuery("#yourSelectsIDHere").trigger("change");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜