0

might be a silly question but im really stuck..Nothing is happening with this code. It's like the js isnt attached properly? Not sure why

add.js

$('select').on('change', function() {
  alert( this.value );
})

html:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="add.js"></script>
</head>

<select>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>
d joe
  • 45
  • 1
  • 7
  • Provide full html. It is important where you do write your js and where you do load jquery. – dhilt Oct 10 '17 at 23:48
  • Possible duplicate of [jQuery get value of select onChange](https://stackoverflow.com/questions/11179406/jquery-get-value-of-select-onchange) – Jack Moody Oct 10 '17 at 23:54

2 Answers2

1

Try following:

./index.html

<html>
  <head>
    <meta charset="utf-8" />
    <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/add.js"></script>
  </head>

  <body>
    <select>
      <option value="1">One</option>
      <option value="2">Two</option>
    </select>
  </body>

</html>

And ./js/add.js

$(function(){
  $('select').on('change', function() {
    alert( this.value );
  })
});
dhilt
  • 18,707
  • 8
  • 70
  • 85
0

Since you provide a relative path, the browser will be looking for your file in the folder relative to the current URL. For example, if your url is http://localhost/some/path and you include script like the following.

<script src="js/add.js" ></script>

The browser will look for your file at http://localhost/some/path/js/add.js

If you want the browser to always look for your file in js folder at the root directory, you can specify an absolute path.

<script src="/js/add.js" ></script>

Now the browser will always look for your file at http://localhost/js/add.js regardless of what your current URL is.

Anurat Chapanond
  • 2,837
  • 3
  • 18
  • 31