Search code examples
javascripthtmlcssformsjsfiddle

Can't get the javascript to work in HTML form in jsfiddle


I am putting together an html form where i can add users to an email distribution list. I am trying to mock this up on jfiddle but for some reason the javascript is not working. When i just save the following code in an html page and try it in a browser it works ok. My question is what is that i am doing wrong in jsfiddle and the javascript function doesn't work. Thanks!

The jsfiddle that is not working is here: MyFiddleExample

My Form

function onAddClicked() {
  var userList = document.getElementById("UserList");
  var distributionList = document.getElementById("DistributionList");

  var newMember = document.createElement('option');
  newMember.value = userList.options[userList.selectedIndex].value;
  newMember.innerHTML = userList.options[userList.selectedIndex].text;

  distributionList.appendChild(newMember);
}
<form>

  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="UserList">Available Users:</label>
      <select class="form-control" name="UserList" size=10 id="UserList">
        <option value="UserA">User A</option>
        <option value="UserB">User B</option>
        <option value="UserC">User C</option>
        <option value="UserD">User D</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" onclick="onAddClicked()" class="btn btn-success btn-block" style="margin-top:33px">Add &gt;&gt;</button>
      <button type="button" class="btn btn-danger btn-block" style="margin-top:33px">&lt;&lt; Remove</button>
    </div>

    <div class="form-group col-md-5">
      <label for="DistributionList">Distribution List Members:</label>
      <select class="form-control" name="DistributionList" size=10 id="DistributionList">
      </select>
    </div>
  </div>
</form>


Solution

  • The problem is specific to JSFiddle. You need to change the LOAD TYPE to No wrap - bottom of <body>.

    When using on DOM load, the function won't become global one, so you can't invoke it directy from HTML. If it is global - like when using no-wrap - it works.