Why can't I call a function named clear from an onclick attribute?

i'm trying to create a simple calculator, when a button is clicked its value is shown in the text field and the button "C" should clear the text field but its onclick="clear()" is not working??

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
        <style>
            #button{
                padding: 10px;
            }
        </style>
        <script>
            function fill(val){
                document.getElementById("field").value+=val;
            }
            function clear(){
                document.getElementById("field").value="";
            }
        </script>
    </head>
    <body>
        <form>
        <table>
            <tr><input type="text" name="field" id="field" size="8"/></tr>
        <%! int k = 1; %>
        <% for(int i=0;i<3;i++){ %>
        <tr> <%
            for(int j=0;j<3;j++){ %>
            <td><input type="button" id="button" onclick="fill(this.value)" value="<%=k++%>" /></td>
          <%  } %>
        </tr>
        <% } %>
        <tr>

<!--here onclick="clear()" is not working?? -->

            <td><input type="button" id="button" value="C" onclick="clear()"/></td>
            <td><input type="button" id="button" value="0" onclick="fill(this.value)"</td>
            <td><input type="submit" id="button" value="="</td>
        </tr>
        </table>
        </form>
    </body>
</html>

Solution 1:

Intrinsic event attributes (like onclick) are horrible. Internally they implement with:

Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.

Consequently, you are actually calling document.clear() instead of your global clear().

The quick fix for this is to rename the function to something else or explicitly call window.clear().

The better solution is to bind your event handlers with addEventListener instead of intrinsic event attributes.

enter image description here

Solution 2:

Your HTML has problems, but the reason your function is not working is because of its name "clear", which is already defined by document.clear().

Change the name of that function to something like clearField() and it will work.