Issue
I'm writing code to show hints to the user in <textarea/>
in grey color;
Idea is next:
- Initially place
'Please, type your inquiry there'
in grey color; - If user clicks on it, color changes to black and text to
''
. This part works fine; - If user types and then deletes (i.e. leave field blank) than we need to put
'Please, type your inquiry there'
in grey color back in.
Step (3) does not work in Chrome nor in Firefox. It displays nothing. When I use Chrome inspector, it shows:
element.style { color: rgb(141, 141, 141); }
which is right, and "Please, type your inquiry there"
in HTML, which is also right. But the field is empty. What might be the problem???
I specifically used console.log()
and they also display output that should be...
This is the HTML and JS code:
<textarea name='contact_text' id='contact_text'
onclick='text_area_text_cl();' onBlur='text_area_text_fill();'>
</textarea>
<script>
var contact_text_changed = false;
var contact_contacts_changed = false;
function text_area_text()
{
if (contact_text_changed == false)
{
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your inquiry there');
}
else
{
$("#contact_text").css("color","#000000");
}
// Write your code here
};
function text_area_text_cl()
{
if (contact_text_changed == false)
{
$("#contact_text").text('');
$("#contact_text").css("color","#000000");
console.log('sdfdfs111');
contact_text_changed = true;
}
};
function text_area_text_fill()
{
if ($("#contact_text").val() == '')
{
contact_text_changed = false;
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your inquiry there');
//document.getElementById('contact_text').innerHTML = 'Please, type your inquiry there'
console.log('sdfdfs');
}
else
{
console.log('__');
}
};
// call functions to fill
text_area_text();
</script>
Solution
To set the value of a <textarea>
you need to use .val()
:
$("#contact_text").val('');
or
$("#contact_text").val('Please, type your enquiry there');
etc. It's tricky to make "placeholder" code work properly. Newer browsers allow:
<textarea placeholder='Please, type your enquiry there' id='whatever'></textarea>
and they manage it all for you.
edit — from the comments, here's an explanation as to why it appears that .html()
works (well, it does work, but read on) initially. The markup contents of a <textarea>
element — that is, the DOM structure contained within the element — represents the initial value of the <textarea>
. Before any user interaction (and/or before the "value" property of the DOM has been touched by JavaScript), that's what's shown as the value of the field. Changing that part of the DOM, then, changes that initial value. Once there's been some user interaction, however, the initial value is no longer relevant to the page view, so it's not shown. Only the updated value is shown.
Answered By - Pointy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.