views:

88

answers:

1

Hi,

I'm trying to achieve the following functionality. Within a form I have multiple fields with the class name .inputField if one of these fields is selected then the div associated with that element should be shown on focus and hidden on blur. However, when I implement the code below on selecting the second element the class is applied to both. Not sure where I'm going wrong?!?!?

html markup:

<form class="friendlyForm" name="friendlyForm" id="friendlyForm">
                                            <ul>
                                                <li>
                                                    <label for="testField">Test field</label>
                                                    <input name="testField" value="here" class="inputField" id="testField" />
                                                    <div class="helper" style="display: none;">helper text here</div>
                                                </li>
                                                <li>
                                                    <label for="testField">Test field2</label>
                                                    <input name="testField2" value="here" class="inputField" id="testField2" />
                                                    <div class="helper" style="display: none;">helper text here</div>
                                                </li>
                                            </ul>
                                        </form>

jQuery markup:

$('.friendlyForm').find('.inputField').each(function(i) {
    $(this).blur();
    $(this).focus(function() {
        //Add the focus class and fadeIn the helper div
        $(this).parent().addClass('focus');
        $(this).parent().parent().find('.helper').fadeIn();
    });
    $(this).blur(function () {
        //Remove the focus class and fadeOut helper div
        $(this).parent().removeClass('focus');
        $(this).parent().parent().find('.helper').fadeOut();
    });
});

Any pointers here would be greatly appreciated.

Thanks

+1  A: 

If I understand your question correctly, this should do the trick.

$('.friendlyForm .inputField').each(function () {
  $(this).blur().focus(function () {
    $(this).parent().addClass('focus');
    $(this).siblings('.helper').fadeIn();
  }).blur(function () {
    $(this).parent().removeClass('focus');
    $(this).siblings('.helper').fadeOut();
  });
});

What you're doing wrong is that you're using parent().parent() which will get the <ul> tag and thus it will find all .helper elements in that <ul>.

Deniz Dogan
I actually think you don't even need the `.each`, you can just do `$('.friendlyForm .inputField').blur().focus(...).blur(...)`.
Deniz Dogan
Thanks, that's done the trick. Simple really!
simnom