I am getting a SelectChanged is not defined
message when using the following code. For the life of me, I cant figure why since I have used this before:
jQuery
jQuery("#name").on("change", function() {
alert(this.value);
});
dropdown
echo('<td class="table-font"><select id="name" onchange="SelectChanged(this)">');
foreach($Staff_On_Duty as $person){
$sf_name_option=$person->Staff_First_Name;
$sl_name_option=$person->Staff_Last_Name;
echo("<option value = $sf_name_option $sl_name_option");
if (($sf_name_option == $sf_name) && ($sl_name_option == $sl_name)) echo (" selected");
echo(">$sf_name_option $sl_name_option</option>");
}
echo("</select></td>");
Yes I am aware that the above method of showing the menu isn't the best, I am working on getting the functionality I need, then can make it better through separating the HTML and PHP etc
You're trying to do the same thing twice.
You can call a function inline using onchange=function()
or you can add a JQuery
event listener using $(elem).on('change', function() {})
.
Your code is actually working (using the jquery event listener) but you are also getting an error from the attempt to run an inline function. The inline function is not defined (i.e. when the select is changed it tries to find a function called SelectChanged
but as it has not been defined you are getting an error).
The example below shows both methods functioning.
// Add a jquery event listener to the element with the id name, listening for any change
jQuery("#name").on("change", function() {
// Print the value of the element
console.log("From JQuery function: " + this.value);
});
// Function that can be called inline using onchange = "SelectChanged(this)"
function SelectChanged(el) {
// Print the value of the inline element
console.log("SelectChanged function: " + el.value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td class="table-font">
<select id="name" onchange="SelectChanged(this)">
<option value="Firstname Surname 1" selected>Firstname Surname 1</option>
<option value="Firstname Surname 2">Firstname Surname 2</option>
</select>
</td>