I have some jQuery that p开发者_开发知识库rovides a placeholder as long as my <label for="">
matches the input
name and ID. However, that's not the case so I've decided to just use a <span>
for the placeholder instead. Can someone help alter my jQuery to make the <span>
class "holder" I'm using work? The goal is to have the placeholder stay on focus, disappear when input exists, then reappear if the input disappears.
Here's the HTML I'm using:
<div id="placeholder">
<span class="holder">This is the placeholder...</span>
<%= f.text_area :body, :id =>"Placeholder" %>
</div>
And my current jQuery:
$(document).ready(function() {
$('textarea').keyup(function() {
if ($(this).val().length) {
$('label[for="' + $(this).attr('name') + '"]').hide();
} else {
$('label[for="' + $(this).attr('name') + '"]').show();
}
});
});
Thanks!
You want to bind to the focus
and blur
events and absolutely position the <span>
over the <textarea>
. Start with some CSS:
#placeholder {
position: relative;
}
.holder {
position: absolute;
top: 2px;
left: 2px;
display: none;
}
And then the jQuery:
$('.holder').click(function() {
$(this).siblings('textarea').focus();
});
$('#Placeholder').focus(function() {
$(this).siblings('.holder').hide();
});
$('#Placeholder').blur(function() {
var $this = $(this);
if($this.val().length == 0)
$(this).siblings('.holder').show();
});
$('#Placeholder').blur();
The final $('#Placeholder').blur()
call is there to initialize the state of the <span>
so that it will be in the right state if the <textarea>
starts out with content.
And a quick demo: http://jsfiddle.net/ambiguous/PLrf3/1/
BTW, having id="placeholder"
and id="Placeholder"
in the same page might lead to some confusion. You would be better off choosing a standard scheme (camelCase
, words-and-hyphens
, or whatever) for your id
attributes and sticking to it. Just a case difference might be confusing and might look like a typo.
Something like this should work:
$(function() {
$("span.holder + textarea").keyup(function() {
if($(this).val().length) {
$(this).prev('span.holder').hide();
} else {
$(this).prev('span.holder').show();
}
});
});
This should work for all textareas on page if they have span.holder
preceding them.
精彩评论