Kyle Dunne Kyle Dunne - 6 months ago 10
Javascript Question

Get value during JQuery change

I have a select menu where when I click a button it populates. This menu then has an on change event where it changes the div below it with whatever is in it. The problem is the first value doesn't work because it isn't a "change".

HTML/PHP Before:

<select>
<option>Pre Fill</option>
</select>


HTML/PHP After:

<option value="<?=$row["ID"]?>"><?=$row["Person"]?></option>


THE PROBLEM

function FillList(str) {
$.get( "get.php?q="+str, function( data ) {
$( "select" ).html( data );
});
var Id = $('select').val();
$.get( "fill.php?q="+Id, function( data ) {
$( ".Info_Div" ).html( data );
});
}


For my
var Id
it returns Pre Fill instead of the first results ID number. I know I can just throw in a blank space so people have to change it. But is there a way I can get it to do it instantly? My change works, the first result doesn't work unless I change off it and change back to it.

Answer

You can trigger the .change() event after the <select> is loaded. It will then run the code that updates the value in the other <div>.

$.get( "get.php?q="+str, function( data ) {
  $( "select" ).html( data ).change();
});

Also, $.get is an AJAX request, which means it won't pause the execution of the script until the response has returned, instead it will continue to execute the statements below. For Id to contain something from the response, it must be inside the response callback.

$.get( "get.php?q="+str, function( data ) {
    $( "select" ).html( data ).change();
    var Id = $('select').val();
    $.get( "fill.php?q="+Id, function( data ) {
        $( ".Info_Div" ).html( data );
    });
});