Search code examples
javascriptdom-eventsinline

Troubleshoot JavaScript onchange


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>

Solution

  • 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>