I am trying to write a simple script that emulates placeholders so that I can use the effect for all browsers. What I created is a form with a range with some text in it, which I absolutely position above the input. It acts like placeholder text.
Now jQuery is quite simple, and if I write out separate functions for each input element, I get it to work fine, but this kind of redundancy. What I'm trying to do is use each () and children () and classes so that I can apply this to any form I want. Here is 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 a warning statement in each function, it works, but it does not execute the rest, which should hide the child class “.inputText” and focus on another child element. "I suppose this has something to do with the fact that it's impossible to call $ (this) again inside the function. Does anyone have any ideas on how I can get this to work?
Solved !!! Thanks Matt. Here's the final working code with a function to put the placeholder text back if the 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>
Throttlehead
source share