Ok so I have the following function:
function hideValue(value) {
if (this.value == value) {
this.value = '';
}
And the following form field:
<input onfocus="hideValue('First Name')" type="text" name="first_name" value="First Name">
I cannot get the function to hide the value. When I alert(value);
in the function, it returns the correct value.
I also have a showValue function which does the opposite. Why are these not working?
Ok so I have the following function:
function hideValue(value) {
if (this.value == value) {
this.value = '';
}
And the following form field:
<input onfocus="hideValue('First Name')" type="text" name="first_name" value="First Name">
I cannot get the function to hide the value. When I alert(value);
in the function, it returns the correct value.
I also have a showValue function which does the opposite. Why are these not working?
this
doesn't refer to the element when you call the function that way (so this.value
is likely undefined).
– nnnnnn
Commented
Apr 21, 2016 at 5:46
In an event handler on a DOM element this
refers to the element only in the first level of the function. Therefore you need to pass this
into the function:
<input
onfocus="hideValue(this,'First Name') /* 'this' is only correct here */"
type="text" name="first_name" value="First Name"
>
The function should therefore be modified to:
function hideValue(element, value) {
if (element.value == value) {
element.value = '';
}
}
I'll remend to use placeholder
for this kind of functionality.
<input type="text" name="first_name" placeholder="First Name" />
^^^^^^^^^^^^^^^^^^^^^^^^
Browser support
Demo:
<input type="text" name="first_name" placeholder="First Name" />
Problem:
this
inside the function hideValue()
refers to the Global window
object.
Solution:
You can pass this
reference to the event handler.
<input onfocus="hideValue(this, 'First Name')"
^^^^
And catch that inside event handler
function hideValue(that, value) {
^^^^ // What is that? `this`
if (that.value === value) {
that.value = '';
}
}
Demo
function hideValue(that, value) {
if (that.value === value) {
that.value = '';
}
}
<input onfocus="hideValue(this, 'First Name')" type="text" name="first_name" value="First Name">
<input onfocus="hideValue(this,'First Name')" type="text" name="first_name" value="First Name">
<script>
function hideValue(thisvalue,value) {
if (thisvalue.value == value) {
thisvalue.value = '';
}
}
</script>
Please check this. Its working fine