Javascript function cannot update variable

Viewed 72

I am trying to update the value of a button with id 'cost' on click. Here is my script :

<script>
    var costObj = document.getElementById('cost');
    function change() {
        costObj.value = 100;
    }
</script>

and here is the input html.

<input type = number id = 'cost' onclick = 'change()'>

This does not work saying that costObj in the function change is null, but putting the costObj declaration within the function seems to work. Why is this so ? I thought the function will look for the declaration outside the function if there is no declaration as is the case for var that has primitive type. This kind of shakes my conceptual understanding. Thank you in advance !

3 Answers

When your code is put into a Stack Overflow "snippet" like this, it works as expected:

var costObj = document.getElementById('cost');
function change() {
    costObj.value = 100;
}
<input type = number id = 'cost' onclick = 'change()'>

I think the culprit is likely to be what @Musa noted in a comment: make sure that your script appears after the <input> tag, otherwise the cost element will not exist at the time you try to get a reference to it.

It works in the snippet because the JavaScript code is loaded after the HTML code. Note that Stack Overflow's presentation of the snippet is a bit misleading, as it displays the HTML below the JavaScript.

To help illustrate this, here are two more versions of the snippet with everything included in the HTML section instead of using the separate JavaScript section. This way we can control whether the HTML or JavaScript code is loaded first.

This one fails because the script is included before the input tag:

<script>
    var costObj = document.getElementById('cost');
    function change() {
        costObj.value = 100;
    }
</script>

<input type = number id = 'cost' onclick = 'change()'>

This one succeeds because the script is included after the input tag:

<input type = number id = 'cost' onclick = 'change()'>

<script>
    var costObj = document.getElementById('cost');
    function change() {
        costObj.value = 100;
    }
</script>

you should to try to add event listener on the object and change var to const for best way and dont use onclick below the html code because its looks like old way to call the function just execute the function inside the listener event

for example

    const costObj = document.getElementById('cost');
    costObj.addEventListener("click" , function(){
        change();
    }); 
    
        function change() {
            costObj.value = 100;
        }
<input type="text" id="cost" />

put below js code and replace onClick = 'change()' with onClick = "change()"

Related