1
<html>
<head>
<script>

function html(el) {
    var html = el.value || '', 
    wysiwyg = document.getElementById('output_html');

    if (html == '') {
    document.getElementById('clear').disabled = true;
    html = 'HTML editor!';
    } else {
    document.getElementById('clear').disabled = false;
    }

    wysiwyg.innerHTML = html;
}
function clear() {
    var html = document.getElementById('input_html'), 
    wysiwyg = document.getElementById('output_html');

    wysiwyg.innerHTML = 'HTML editor!';
    html.innerHTML = '';
}
</script>
</head>
<body onload="javascript:document.getElementById('clear').disabled = false;">
    <div id="output_html">HTML editor!</div>
    <input id="clear" type="submit" onclick="clear()" value="Clear"/>
    <textarea id="input_html" onKeyUp="html(this)" placeholder="Type HTML!"></textarea>
</body>
</html>

I wanted to learn JavaScript and fool around with it, but I came across a problem.

When I type things on the textarea, it auto updates as i want it to.

When I press on "Clear" it should clear, but it wont. Why is it doing this?

buhbang
  • 715
  • 1
  • 7
  • 18
  • Possible duplicate: http://stackoverflow.com/questions/7165570/is-clear-a-reserved-word-in-javascript – Dennis Oct 13 '11 at 23:17

2 Answers2

1

The shortest answer is don't use inline handlers. These run with document scope, so it will try to run document.clear() before going up one more level and finding the global window.clear(), which is your function.

window.onload = function() {

    document.getElementById("input_html").onkeyup = function () {
        var html = this.value || '', 
        wysiwyg = document.getElementById('output_html');

        if (html == '') {
            document.getElementById('clear').disabled = true;
            html = 'HTML editor!';
        } else {
            document.getElementById('clear').disabled = false;
        }
        wysiwyg.innerHTML = html;
    }

    document.getElementById("clear").onclick = function () {
        var html = document.getElementById('input_html'), 
            wysiwyg = document.getElementById('output_html');
        wysiwyg.innerHTML = 'HTML editor!';
        html.value = '';
    }
}

HTML:

<body>
    <div id="output_html">HTML editor!</div>
    <input id="clear" type="submit" value="Clear"/>
    <textarea id="input_html" placeholder="Type HTML!"></textarea>
</body>
Dennis
  • 32,200
  • 11
  • 64
  • 79
0

Long story short, you want to set the value of the textarea, not its innerHTML.

Stephen
  • 5,362
  • 1
  • 22
  • 33