0

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>
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
SNicolaou
  • 550
  • 1
  • 3
  • 15
  • If it works in a browser but not in JSFiddle, it's either a copy/paste error or a bug in JSFiddle. – Jack Bashford Dec 20 '18 at 11:31
  • You use jquery in jsfidle, try with this code and use jquery : $('.btn-success').click(function() { if(val != undefined) { var val = $("select#UserList option:checked").val(); $("select#DistributionList").append($(' – Shim-Sao Dec 20 '18 at 11:57
  • Thanks for the recommendation Shim-Sao, i will keep that in mind, but the purpose of the question was to understand why the jsfiddle wasn't working. – SNicolaou Dec 20 '18 at 11:59

1 Answers1

1

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.

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57