7
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<body>

<button type="button" onclick="submit();">launch</button>
<button type="button" onclick="clear();">clear</button>


<div>
    Result:<br>
    <div id="result">
    </div>
</div>
<script>
    function clear() {
        $('#result').empty()
    }

    function submit() {
        $('#result').append('<div>xxxxx</div>')
    }
</script>
</body>
</html>

Launch button works well but clear doesn't. I run $('#result').empty() in console, it clear the div as expected.

You may debug my code in jsfiddle.

Sayakiss
  • 6,878
  • 8
  • 61
  • 107

6 Answers6

11

Calling clear() in an inline handler is actually calling something else called document.clear(), and so your function is never called.

This is because in an inline handler, document is in scope before window and your clear function is in the global scope, which is window for browsers.

You can change the function name to something else

<button type="button" onclick="myClear();">clear</button>

function myClear() {
    $('#result').empty()
}

Alternatively I would prefer to avoid inline handlers and also avoid polluting the global scope.

$(function(){
    function clear() {
        $('#result').empty();
    }

    $('.clear').click(function(){
        clear();
    });
});
MrCode
  • 63,975
  • 10
  • 90
  • 112
2

It's because clear is calling the function document.clear() which comes first in the considered scope that is inline HTML call.

Try to rename your function it to anything else.

Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
1

clear is a reserved word, rename it to something else

rorypicko
  • 4,194
  • 3
  • 26
  • 43
1

Seems like your .empty() is working. The problem here is clear() function is not getting called. I tried changing clear() to clear1() and it worked.

0

Just set it using

$('.textboxElement').val("");

instead of clear. I'm not sure why your clear isn't working, but this is another way of doing it. Maybe your method name is being picked up? Try naming it to 'foo'

TechnicalTophat
  • 1,655
  • 1
  • 15
  • 37
0

The problem is your function name. "Clear" is already defined as document.clear so it is not hitting your code. Rename your function to something like clearContent.

hooda
  • 105
  • 6