简体   繁体   中英

Jquery looking to trigger select box change

Hey ii have select box with long method binded to it to its the select box in the html looks like this :

HTML:

<select id="select1">
  <option>First select Advertiser</option>
  <?php
     buildSelectOptionsFromPagination();  // Dynamically build the options list
  ?>
</select> 

Javascript:

$('#select1').change(function(){
                alert('#select1');
                $('#innerP').remove();
                $('#innerH').remove();
                $('#waitmsg').append('  ...</h2></p>');
                $("#show_c ").attr("disabled", true);   


                 $.ajax({
                        url: 'observer.php',
                        data: "ctrl=in&v_id="+v_id,
                        success: function(data) {
                             var newData = "<option id=\"firstopt_insert\"> blah blah <\/option>" + data;
                             $('#in111').html(data);
                             $('#in222').trigger('change');

                        },
                        error: function (request, status, error) {
                            alert(request.responseText+"\nThere was an server error please refresh the page 1 ");
                        }                           
                });
            });

now i try to trigger this select box change method without success from out side i trigger 2 method , 1. select option by index with this which works great :

$('#select1 option')[5].selected = true;

2 now i want to trigger the change method method without success like this :

$('#select1').trigger('change');
or 
$('#select1').bind('change', function(){ ; });

and its just don't trigger any thing , why ?

Change event is triggered when user selects an option. It's not triggered when you are setting the value via jQuery val() method of by setting option's selected attribute to true. So you have to trigger change event manually.

Your code

$('#select1').trigger('change');

should work. Maybe, it doesn't because you code raising an error. This may happen in this place

$('#select1 option')[5].selected = true;

because here you don't perform array's range checking.

Better way is to select needed option by index like this:

$('#select1 > :nth-child(6)').prop('selected', true);

This way code wouldn't crach in case if there is no 6th option.

However, this fiddle , built from your example, works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM