Search code examples
jqueryformsselectedvalue

I'm having issues setting selected in dropdown with jQuery


See example here. Clicking [Email Me] in the President's header should open up the contact form with Webmaster selected from the dropdown, but that's not happening.

I know it should be trivial, but it's not turning out that way. get stuff in email() is working alright but when it gets to the selecting an option, the code craps out. All relevant code is below.

My HTML:

<form method="get">
    <select name="to" id="to-field">
      <option name="President" value="President">President</option>
      <option name="Webmaster" value="Webmaster">Webmaster</option>
    </select>
</form>

My JS/jQuery:

function email(to){
    $(document).ready(function() {
         $.get('/inc/email.php', 
               function(data){
                    $('#email-form').html(data);
                    $('#email-form form').submit( function(){
                        var d = $('#email-form form').serialize();
                        $.ajax({
                          type:     'GET',  
                          url:      '/inc/email.php?submit=true&'+d,
                          success:  function(data) {
                                        $('#email-form').html(data);
                          }
                        });
                        return false;
                    });
            }
         );
     });

    if(to !== undefined){
        $('select#to-field').val(to);
        console.log( 'item selected -> ' + $('select#to-field').val() );
    }
}

This is being triggered by:

<span onclick="javascript:email('Webmaster');">[Email Me]</span>

And console.log() is returning:

item selected -> undefined

I've also tried setting selected using this:

$("select#to-field[value=" + to + "]").attr("selected","selected");

And even this for good measure:

$("select#to-field[value=" + to + "]").attr("selected",true);

Any help would be greatly appreciated!


Solution

  • Your $.get is an async event!! As it is, your

    if(to !== undefined){
            $('select#to-field').val(to);
            console.log( 'item selected -> ' + $('select#to-field').val() );
        } 
    

    will execute before the inner email page is even finished loading! Put that part inside your $.get callback to be done after the email page is loaded!

    Put it between like this

    $('#email-form').html(data);
    //RIGHT HERE
        if(to !== undefined){
                $('select#to-field').val(to);
                console.log( 'item selected -> ' + $('select#to-field').val() );
            } 
    //
    $('#email-form form').submit( function(){...