1

I am new to javaScript, that's why I am unable to find the real root cause for it. This simple code is to append the value of a button into a paragraph every time i press it; however if the paragraph contains only a zero then it should replace the value, not append.

  1. This is working fine on all of my browsers and also when running the snippet on stackoverflow .
  2. Not working at all on https://jsfiddle.net/

Can you please tell me why I am facing this problem and what changes should I make to make it work on every platform?

function append(a){
  if (document.getElementById('text1').innerHTML == '0')
    document.getElementById('text1').innerHTML = document.getElementById(a).value;
    else
    document.getElementById('text1').innerHTML += document.getElementById(a).value;
};
<div>
<p id='text1' style="border-style: inset;
         width:200px;
         display:inline-block;">0</p><br>
<button value="1" id='a1' onclick="append(this.id)">1</button></div>
  
  • 5
    In JSFiddle, you need to change your JavaScript *Load Type* to `No wrap - in `. By default, scripts on JSFiddle are wrapped within a document load handler, therefore `append` is not declared in the same scope as the element. – Tyler Roper Apr 19 '17 at 18:03
  • 3
    Because jsFiddle thought it would be a good idea to put all your JS code inside a function without making it clear. So your `append()` function isn't global. As a result of their design decision, there are hundreds of questions like yours on StackOverflow. –  Apr 19 '17 at 18:03

1 Answers1

2

By default JSFiddle wraps your JavaScript in an onload function. This means that function append is only defined in that scope, and is not made global.

Global variables (and functions) are generally considered bad practice, as are inline event handlers.

Try:

document.getElementById('a1').onclick = append;

Then, inside function append, simply refer to this.value.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592