Aseem Sharma
Aseem Sharma

Reputation: 149

JavaScript - code is not working - passing argument to function

I am trying to understand bookmark application which I found on internet,here is the link for the code https://github.com/bradtraversy/bookmarker/blob/master/js/main.js Now in that code on line 85 he build button element with onclick event,assign it to function deleteBookmark() and passed the argument url in it which then get recieved in deleteBookmark() function on line 55 and his code works but when I tried to build similar kind of code to better understand what is happening in that application,my code does not work. I am using the code below.

    <div id="divArgument"></div>
    <input type="text" id="argument">
    <p id="displayArg"></p>
    <script>
    var testArg = document.getElementById('divArgument');
    var getVal = document.getElementById('argument').value;
    testArg.innerHTML = '<button onclick="sendArg(\''+getVal+'\')">Display Argument</button>';

    function sendArg(recVal){
            document.getElementById('displayArg').innerHTML = recVal;
        } 
    </script>

Upvotes: 1

Views: 42

Answers (1)

brk
brk

Reputation: 50291

When '<button onclick="sendArg(\''+getVal+'\')">.... is executed getVal does not hold any value.

So put var getVal = document.getElementById('argument').value; inside the event handler function

var testArg = document.getElementById('divArgument');
testArg.innerHTML = '<button onclick="sendArg()">Display Argument</button>';

function sendArg(recVal) {
var getVal = document.getElementById('argument').value;
  document.getElementById('displayArg').innerHTML = getVal;
}

DEMO

Upvotes: 2

Related Questions