I have an input field:
<input name="Name" value="Enter Your Name">
How would I get it to remove the pre-defined text (Enter Your Name) when the user clicks the box.
As far as I am aware Javascript is the best way to do this. If that wrong please inform me.
Description. The onclick property of an Input object specifies an event handler function that is invoked when the user clicks on the input element. It is not invoked when the click( ) method is called for the element. Only form elements that are buttons invoke the onclick event handler.
To clear an input element, simply set its value to an empty string.
You are likely wanting placeholder
functionality:
<input name="Name" placeholder="Enter Your Name" />
This will not work in some older browsers, but polyfills exist (some require jQuery, others don't) to patch that functionality.
If you wanted to roll your own solution, you could use the onfocus
and onblur
events of your element to determine what its value should be:
<input name="Name" value="Enter Your Name"
onfocus="(this.value == 'Enter Your Name') && (this.value = '')"
onblur="(this.value == '') && (this.value = 'Enter Your Name')" />
You'll find that most of us aren't big fans of evaluating JavaScript from attributes like onblur
and onfocus
. Instead, it's more commonly encouraged to bind this logic up purely with JavaScript. Granted, it's a bit more verbose, but it keeps a nice separation between your logic and your markup:
var nameElement = document.forms.myForm.Name;
function nameFocus( e ) {
var element = e.target || window.event.srcElement;
if (element.value == "Enter Your Name") element.value = "";
}
function nameBlur( e ) {
var element = e.target || window.event.srcElement;
if (element.value == "") element.value = "Enter Your Name";
}
if ( nameElement.addEventListener ) {
nameElement.addEventListener("focus", nameFocus, false);
nameElement.addEventListener("blur", nameBlur, false);
} else if ( nameElement.attachEvent ) {
nameElement.attachEvent("onfocus", nameFocus);
nameElement.attachEvent("onblur", nameBlur);
}
Demo: http://jsbin.com/azehum/2/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With