Search code examples
jqueryselectedindex

Jquery $(this).prop('selectedIndex', num) not working


The line of code mentioned above does work usually, but not when I move it into the function (data) return from my php script. I'm assuming something is out of scope or something like that? Here's the code, stripped down to the basics.

$('.training_staff_change').on('change',
    function () {

        // Post the data.
        $.post('updatetrainingstaff.php',
            {
            } ,
        function ( data ) {
            $(this).prop('selectedIndex', 5);   
        }
        )
});

As I say, that's stripped down, the rest of the code is working fine. If I move the line out of the function and below the ) it works fine and sets the selector as required. Is $(this) out of scope here or something? In my final code, it will change the selectedIndex to the 'data' return value, but that's not the issue here. It won't even change it to a straight '5'.


Solution

  • Yes, it's out of scope (you self-answer your question), but to solve this there are so many ways, the simplest way is this:

    $('.training_staff_change').on('change',
        function () {
            var that = $(this);
            // Post the data.
            $.post('updatetrainingstaff.php',
                {
                } ,
            function ( data ) {
                that.prop('selectedIndex', 5);   
            }
        )
    });