Troubleshoot JavaScript onchange

75 Views Asked by At

When I use these scripts (inline and external) together only second one works, and first one - not.

First one (inline script) submits the form and loads the list:

<select id="my-select" name="show_user_todo" onchange="document.form_buttons.submit()">

Second one sets the color of select according to selected option:

<script type="text/javascript">
  var mySelect = document.getElementById('my-select');

  var setBgColor = function (select) {
    select.style.color = select.options[select.selectedIndex].style.color;
  };

  mySelect.onchange = function () {
    setBgColor(this);
  };
</script>
1

There are 1 best solutions below

9
On BEST ANSWER

you can do like this

<select id="my-select" name="show_user_todo">

<script type="text/javascript">
    var mySelect = document.getElementById('my-select');

    var setBgColor = function (select) {
      select.style.color = select.options[select.selectedIndex].style.color;
    };

    mySelect.onchange = function () {
      setBgColor(this);
      document.form_buttons.submit();
    };
</script>