How to change the text of textbox/input by JavaScript, when its clicked
var txtSearch = document.getElementById("txtSearch");
txtSearch.onmousedown= txtClear;
function txtClear() {
txtSearch.value = "";
}
How to change the text of textbox/input by JavaScript, when its clicked
var txtSearch = document.getElementById("txtSearch");
txtSearch.onmousedown= txtClear;
function txtClear() {
txtSearch.value = "";
}
You need to assign the handler after the DOM is loaded:
window.onload = function() {
var txtSearch = document.getElementById("txtSearch");
txtSearch.onmousedown= txtClear;
};
Otherwise, it can't find the txtSearch
element if your Javascript appears before the body of the HTML.
Ahh, so if I'm correct...this is actually a common early mistake. I'm assuming this is your whole Javascript? It's not wrapped in any function? If that's the case, this question also should help with the answer:
You'll want to use an event listener on your object and use the focus
event like so (assuming the element in question here is an input):
document.getElementById("txtSearch").addEventListener("focus", function(event) {
event.target.value = txtClear();
});
Note that you don't have to use a function
to set the value (and if you do, you'll need it to return
the value you want, or pass it the event
as a parameter and modify that object); you could just as easily use an empty string (event.target.value = ''
).
You can do it with just one line and still working:
document.getElementById("txtSearch").onmousedown = function() { this.value = "" }
What you are doing is writing code that alters an internal variable. You did nothing to write that information to the page or "screen", if you will. The variable foo.value is more for the use of capturing text or a value, rather than writing it out.
Use document.write(xxxx); as a method to write something to a page or alter the existing HTML.