0

I want to select a user name and print something once the name is selected. However, why is "load_new_content()" not defined?

<html>
<head>
<title>Profile Editor</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js">
$(document).ready(function() {
   $("#selectedUserId").change(load_new_content());
 });

function load_new_content() {
    alert("hello");
 }

 </script>
 </head>
 <body>

 <?php
 error_reporting(-1);
 require('Db.php');

 $db = new Db();
 // var_dump($db);
 $userIds = $db -> getUserIds();
 echo '<select name="selectedUserId" id="selectedUserId" onchange="load_new_content()">';
 echo '<option value="">Choose your CEC User Id</option>';
 foreach($userIds as $ID) {
    echo "<option>".$ID["user_id"]."</option>";
    // echo $userId["user_id"];
    // echo $ID['user_id'];
 }
 echo '</select>';

 ?>
Jonathan Kittell
  • 7,163
  • 15
  • 50
  • 93
  • a side note. http://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean – RisingSun Aug 24 '15 at 22:48

3 Answers3

4

Wrong <script> tag declaration.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <!-- Need this close tag -->

<script> <!-- Need a Open tag -->

$(document).ready(function() {
   $("#selectedUserId").change(load_new_content());
 });

function load_new_content() {
    alert("hello");
 }

 </script>
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1

This can be solved by wrapping the call to load_new_content in a function:

$("#selectedUserId").change(function(){ load_new_content(); });

Also, you are not closing the <script> tag that calls jQuery, or opening a new <script> tag for the subsequent code. Try:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $("#selectedUserId").change(load_new_content());
});
function load_new_content() {
   alert("hello");
}
</script>
GluePear
  • 7,244
  • 20
  • 67
  • 120
1

Two problems. First one noted by others, you need a separate script tag for your inline JavaScript.

Second, you can't just do

$("#selectedUserId").change(load_new_content());

This will just execute the function once when the page loads.

You need to do it like this:

$("#selectedUserId").change(function() { load_new_content() });

(note the function call within another function)

or this:

$("#selectedUserId").change(load_new_content);

(note the lack of parenthesis)

rjdown
  • 9,162
  • 3
  • 32
  • 45