0

I am using the following Javascript to populate another form based on a dynamic select using PHP/Mysql.

This works great but I also want this to trigger when I send a URL string use _GET. I've configured the select element to use this as default:

<option value="<?php echo $_GET['EmpNumber'] ?>"><?php echo $_GET['EmpFirstName'] ?> <?php echo $_GET['EmpLastName'] ?></option>

But when I call the page with values for EmpNumber,EmpFirstName and EmpLastName in the URL, the below script does not trigger. How do I achieve this as well?

<script>
      $(document).ready(function() {    
$('select').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
   if(valueSelected){
           $.ajax({
            type: "POST",
            cache: false,
            url: "getinfo.php",
            data: "data="+valueSelected,
            dataType: "html",
            success: function(res) 
            {

               //alert(res);
          $('#Name').val(res + '\'s');
            },
            error: function(xhr, ajaxOptions, thrownError)
            {

            },
            async: false
        });
   }

   else {
        $('#Name').val('Value');
   }




   //alert(valueSelected);
});
});
</script>

1 Answer 1

2

If I'm understanding the question correctly you want to trigger the same functionality for the change event when the page first loads. That's really simple:

$('select').on('change', function() {
    // some code
}).trigger('change');

That last part, .trigger('change') (or just .change() for short), will execute the function you just bound to the change event for those elements, as if the user had selected a new value.

Sign up to request clarification or add additional context in comments.

2 Comments

Where should I put the trigger in the context of the code? This did not work for me: async: false }).trigger('change');
@RoccoTheTaco It goes immediately after the closing bracket for the call to .on(), as I demonstrated in my answer. In your code, that would be the second to last line as far as I can make out, the one just below the commented out alert.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.