简体   繁体   中英

Second inputs onclick() function doesn't work

There were similar questions, but not exactly what I'm looking for. I have a filter for my table with 1 button that changes the value of a textbox to the currant date. That works fine, but right next to it, theres a button to clear the content in the textbox. This second button doesnt seem to work.

My code:

 function today() { var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); var yyyy = today.getFullYear(); today = yyyy + '.' + mm + '.' + dd; document.getElementById("myInput").value = today; } function clear() { document.getElementById("myInput").value = ""; }
 <div class="form-inline"> <label for="myInput">Filter By:</label> <input class="input-xsmall" type="text" maxlength="10" placeholder="yyyy.mm.dd" id="myInput" style="width: 100px; margin-bottom: 10px; display: inline-block"> <input type="button" value="Today" onclick="today()"> <input type="button" value="Clear" onclick="clear()"> </div>

Not sure how to get it to work. When I switched the onclick function in the first input as clear() it worked so for some reason the second input button doesnt work. How can I fix that?

Try to change the name of that clear() function. And also consider looking into event handlers .

You need to change the js function name from clear() to something else. Because clear() is a javascript built in function/method. Javascript Clear fields Function Not Working?

clear is not a reserved keyword. It is a scope problem

But still if you want to use same function name. can try below code.

Changing your existing function onClick="clear()" to window.clear() can fix your issue.

Refer this Ans

<input type="button" value="clear" onclick="window.clear()">

Unlike what is written here, clear is not a word reserved in js .

Here is the list of reserved words( from s3 site ) 这是保留字列表

Felix Kling Explained here , why sometimes it acts as a reserved word

Or just add an event listener instead

document.querySelector("[type='button'][value='Clear']").addEventListener("click", clear);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM