1

I've got some javascript which I want to be executed and change a list element when a button is clicked:

<button id="click-me" type="button">
     <img  src="https://cdn4.iconfinder.com/data/icons/basic-ui-elements/700/07_plus-128.png" alt="Add to Event" style="width: 50px"/>
</button>

<div>
   <p>Meeting Participants:</p>
   <ol id ="list">

   </ol>
</div>

Javascript/JQuery:

var List = document.getElementById('list');

$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();

        document.getElementById('list').style.backgroundColor = "green";
        var entry = document.createElement("li");
        var testText = document.createTextNode("test")
        entry.appendChild(testText);
        List.appendChild(entry);

        return false;

    });
});

The background colour is successfully turned green, but no list element can be seen to be added. Why isn't my code working? Thanks

6
  • 3
    Your code works fine: jsfiddle.net/RoryMcCrossan/ay4m05rq. Have you checked the console for errors? Also note that you can make the code much simpler if you use jquery alone: jsfiddle.net/RoryMcCrossan/ay4m05rq/2 Commented Jan 25, 2016 at 11:16
  • The variable List must be undefined, Move var List = document.getElementById('list'); inside $(function (){ ... }); Commented Jan 25, 2016 at 11:17
  • @Satpal even better if it is moved inside click event handler to ensure that list element was created when click event happened Commented Jan 25, 2016 at 11:18
  • the thing is, I'm intending later on to use that List on form submit Commented Jan 25, 2016 at 11:19
  • 1
    @SCraig then initialize it again before doing form submit Commented Jan 25, 2016 at 11:20

2 Answers 2

1

just put List initialization inside click event handler

$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();

        var List = document.getElementById('list');
        document.getElementById('list').style.backgroundColor = "green";
        var entry = document.createElement("li");
        var testText = document.createTextNode("test")
        entry.appendChild(testText);
        List.appendChild(entry);

        return false;

    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

A jQuery implementation, as you're already using the library:

$(function (){
    $("#click-me").click(function (e){
        $('#list').prepend('<li>test</li>').css('background-color', 'green');
        return false;
    });
});

https://jsfiddle.net/nc9guq2r/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.