简体   繁体   中英

jQuery change event doesn't fire on specified selector

I have the following code:

$("select.form-control").change(function () {
    alert($(this).val());
});

In my DOM there is a variable number of select tags that I need to work on, but I can't seem to access their values (in this case, their values) using the above function. Any idea why this is not working?

Edit:

The piece of code that should trigger the event:

     <div class="box box-solid ship-grid">
            <div class="box-header with-border">
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                    <h3 class="box-title">Victory II-Class Star Destroyer</h3>
                    <input type="hidden" value="2" name="ship-id-0" id="ship-id-0">
                </div>
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                    <h3 class="box-title points-counter GreenBold"><span class="point-counter" id="point-counter-0">85</span> points 
                    <i class="fa fa-times delete-from-grid" title="Delete this ship" onclick="deleteShipGrid(this)"></i></h3>
                </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
                <div class="col-lg-3 col-md-4 col-sm-12 col-xs-12">
                    <img src="images/ships/empire/victory-II.png" class="ship-grid-image amd-center-img">
                </div>
                <div class="col-lg-9 col-md-8 col-sm-12 col-xs-12">

                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/officer.png" class="grid-upgrade-icon"> Select an Officer</span>
                        <select name="officer-0" id="officer-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No officer</option><option class="tooltip-upgrade-12" value="12">[ +3 ] Director Isard •</option><option class="tooltip-upgrade-13" value="13">[ +3 ] Defense Liason </option><option class="tooltip-upgrade-14" value="14">[ +3 ] Weapons Liason </option><option class="tooltip-upgrade-15" value="15">[ +3 ] Veteran Captain </option><option class="tooltip-upgrade-11" value="11">[ +7 ] Wulff Yularen •</option><option class="tooltip-upgrade-10" value="10">[ +10 ] Admiral Chiraneau •</option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/weapons.png" class="grid-upgrade-icon"> Select a Weapons Team</span>
                        <select name="weapons-team-0" id="weapons-team-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No weapons team</option><option class="tooltip-upgrade-17" value="17">[ +5 ] Sensor Team </option><option class="tooltip-upgrade-18" value="18">[ +6 ] Flight Controllers </option><option class="tooltip-upgrade-16" value="16">[ +7 ] Gunnery Team </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/off.png" class="grid-upgrade-icon"> Select an Offensive Retrofit</span>
                        <select name="offensive-retro-0" id="offensive-retro-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No offensive retrofit</option><option class="tooltip-upgrade-46" value="46">[ +5 ] Expanded Hangar Bay </option><option class="tooltip-upgrade-47" value="47">[ +5 ] Point-Defense Reroute </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/turbo.png" class="grid-upgrade-icon"> Select Turbolasers</span>
                        <select name="turbolasers-0" id="turbolasers-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No turbolasers</option><option class="tooltip-upgrade-36" value="36">[ +5 ] XX-9 Turbolasers </option><option class="tooltip-upgrade-38" value="38">[ +6 ] X-17 Turbolasers </option><option class="tooltip-upgrade-35" value="35">[ +8 ] H9 Turbolasers </option><option class="tooltip-upgrade-37" value="37">[ +10 ] Enhanced Armament </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/ion.png" class="grid-upgrade-icon"> Select Ion Cannons</span>
                        <select name="ions-0" id="ions-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No ion cannons</option><option class="tooltip-upgrade-39" value="39">[ +4 ] Leading Shots </option><option class="tooltip-upgrade-40" value="40">[ +5 ] Ion Cannon Batteries </option><option class="tooltip-upgrade-41" value="41">[ +8 ] Overload Pulse </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/title.png" class="grid-upgrade-icon"> Select a vessel title</span>
                        <select name="tilte-0" id="title-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No title</option><option class="tooltip-upgrade-32" value="32">[ +8 ] Warlord •</option><option class="tooltip-upgrade-33" value="33">[ +5 ] Corrupter •</option><option class="tooltip-upgrade-34" value="34">[ +12 ] Dominator •</option>
                        </select>
                    </div>
                    <div class="checkbox col-md-12" style="margin-top: 20px;">
                      <label>
                        <input type="checkbox" name="flagship-0" id="flagship-0"> Use this ship as flagship
                      </label>
                    </div>
                </div>
            </div>
            <!-- /.box-body -->
    </div>

Imagine I have more than one of these boxes, and I need a unique function to get every select value plus thier name attribute.

A big part of the Javascript code is the following:

$(document).ready(function () {
    $("#grid").css("height", $("#selector").css("height"));

    <?php if($faction_char == 'e'){ ?>
    $("#li-fge").addClass("active");
    <? }else{ ?>
    $("#li-fgr").addClass("active");
    <? } ?>

    var ship_counter = 0;
    var squadron_counter = 0;

    // List object to be populated on submit
    var list = new Object();

    var ship_array = new Array();
    var squadron_array = new Array();

    $('.boostrap-slider').slider();

    $('#points-slider').slider().on('slide', function (ev) {
        setTotalPoints();
    });

    $('#total-points').bind("DOMSubtreeModified", function () {
        checkPoints();
    });

    $('#current-points').bind("DOMSubtreeModified", function () {
        checkPoints();
    });

    $(".ship-selector").click(function () {
        var ship_id = $(this).attr("ship-id");
        var vessel = $(this).attr("vessel");

        // Ship object initialization
        var ship_object = new Object();
        ship_object.builder_id = 0;
        ship_object.list_id = 0;
        ship_object.ship_id = 0;
        ship_object.officer_id = 0;
        ship_object.weapons_team_1_id = 0;
        ship_object.support_team_1_id = 0;
        ship_object.offensive_retrofit_1_id = 0;
        ship_object.defensive_retrofit_1_id = 0;
        ship_object.ordnance_1_id = 0;
        ship_object.turbolasers_1_id = 0;
        ship_object.ion_cannons_1_id = 0;
        ship_object.weapons_team_2_id = 0;
        ship_object.support_team_2_id = 0;
        ship_object.offensive_retrofit_2_id = 0;
        ship_object.defensive_retrofit_2_id = 0;
        ship_object.ordnance_2_id = 0;
        ship_object.turbolasers_2_id = 0;
        ship_object.ion_cannons_2_id = 0;

        $.ajax
                ({
                    type: "POST",
                    url: "server/get_ship.php",
                    data: {
                        'id': ship_id,
                        'vessel': vessel,
                        'counter': ship_counter
                    },
                    cache: false,
                    success: function (data) {
                        $("#ship-grid").append(data);
                        ship_object.builder_id = ship_counter;
                        ship_object.ship_id = parseInt($("#ship-id-" + ship_counter.toString()).val());
                        ship_array.push(ship_object);
                        ship_counter++;
                    },
                    error: function () {
                        alert("AJAX error.");
                    }
                });
    });

    $("select.form-control").change(function () {
        alert($(this).val());
    });

    $("#objective_1").change(function () {
        $.ajax
                ({
                    type: "POST",
                    url: "server/get_objective.php",
                    data: {
                        'id': $("#objective_1").val()
                    },
                    cache: false,
                    success: function (data) {
                        var domData = $.parseJSON(data);
                        $("#obj-1-img").attr("src","images/objectives/" + domData["rows"][0]["cell"][7]);
                    },
                    error: function () {
                        alert("AJAX error.");
                    }
                });
    });

You mention ajax loading. Use a delegated event handler, attached to a non-changing ancestor element (eg document ):

eg add this

$(function(){
    $(document).on('change',"select.form-control", function () {
        alert($(this).val());
    });
});

JSFiddle: http://jsfiddle.net/3p1rtjb0/1/

Delegated events work by listening for the event to bubble up to the ancestor. It then applies the selector to only the elements in the bubble-chain (so is very efficient). It then calls the function on any matching elements that caused the event.

The upshot is that the elements only need to match at event time (not when the event was registered).

Note: I last yeat found a bug, related to styling, that means delegated mouse events attached to body do not fire (if the calculated body height is 0). For that reason I recommend you always use document as the default for delegated event handler (if nothing else is closer/convenient).

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