Burning Hippo
Burning Hippo

Reputation: 805

jQuery .change() not responding as expected

I have a select that I am trying to do a jQuery .change event on. For some reason it is not recognizing the id of the select. It is built through another AJAX call to a php file that creates the select and its options.

<script>
    $(document).ready(function()
    {
        $("#unitselector").on('change', function()
        {
            console.log('made it');
            var unit=$('#unitselector').filter(':selected').val();
            var dataString = {unit:unit};
            console.log(dataString);
            $.ajax({
                type: "POST",
                url: "classes/unit_info.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $('.unitinfo').html(html);
                }
            });
        });
    });
    </script>

relevant PHP:

    echo '<select id="unitselector" name="units">';
while( $row = mysqli_fetch_assoc($result))
{
    $units[] = $row['unit_name'];
    echo '<option value="'.$row['unit_name'].'">'.$row['unit_name'].'</option>';
}
echo '</select>';

Upvotes: 0

Views: 44

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50787

It is built through another AJAX call to a php file that creates the select and its options.

That means it's dynamically added to the DOM and as such requires event delegation. jQuery 1.7+ uses the .on() method in order to bind properly.

$("#unitselector").on('change', function()

to

$(document).on('change', '#unitselector', function()

Further, there's really no reason to try and get the value like you're doing. You're inside of the element and therefore can access it through this which is the native javascript object, or $(this) which is a jQuery object, either way will work fine.

var unit = $(this).val();
//or
var unit = this.value;

Upvotes: 1

Related Questions