I'm trying to write a simple script that emulates placeholders so that I can use the effect on all browsers. What I set up is a form with a span with some text in it that I absolutely position over the input. This acts like the placeholder text.
Now the Jquery is easy enough, and if I write out individual functions for each input element I get it to work fine, but that's kind of redundant. What I'm trying to do is use each() and children() and the classes so that I can apply this to any form I want. Here's the code:
<form id="signupForm" name="signupForm">
<span class="inputSpan">
<input value="" class="input" name="fistName" id="firstName" type="text" />
<span class="inputText" id="inputText">First name</span>
</span>
<span class="inputSpan">
<input value="" class="input" name="lastName" id="lastName" type="text" />
<span class="inputText" id="inputText">Last name</span>
</span>
</form>
<script type="text/javascript">
$('.inputSpan').each(function() {
$(this).children('.inputText').click(function(index) {
$(this).children('.inputText').hide();
$(this).children('.input').focus();
});
});
</script>
If I put an alert statement within the each function, it works, but it's not performing the rest of it which is to hide the child class '.inputText' and focus on the other child '.input' I'm guessing it has something to do with not being able to call $(this) again once inside a function. Anyone have any ideas on how I can get this to work?
Solved!!! Thanks Matt Here's the final working code with the function to put placeholder text back in place if input is left blank.
<script type="text/javascript">
$('.inputSpan').each(function() {
var $input = $(this)
$(this).children('.inputText').click(function(index) {
$input.children('.inputText').hide();
$input.children('.input').focus();
});
$(this).children('.input').focusout( function() {
if ($input.children('.input').attr('value') == '') {
$input.children('.inputText').show();
}
});
});
</script>
Untested, but I believe you're having a scope issue related to $(this)
$('.inputSpan').each(function() {
var $input = $(this)
$(this).children('.inputText').click(function(index) {
//within this click handler, $(this) refers to the the '.inputText' not '.inputSpan'
$input.children('.inputText').hide();
$input.children('.input').focus();
});
});
Using your code...
$(function() {
$(".inputSpan").each(function() {
$(this).children(".inputText").click(function() {
$(this).hide();
$(this).siblings(".input").focus();
});
});
});
Here's a jsFiddle: http://jsfiddle.net/hNXaF/
A simpler way...
$(function() {
$(".inputText").click(function() {
$(this).hide();
$(this).siblings(".input").focus();
});
});
Here's a jsFiddle for this technique: http://jsfiddle.net/R6Vbb/
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