views:

35

answers:

1

I have a form element defined as:

<div class="field">
    <div class="name">
        <label for="User_LastName">
            Last name: <span class="asterisk">*</span></label>
    </div>
    <div class="value">
        <%= Html.TextBox("User.LastName", Model.LastName)%>
        <%= Html.ValidationMessage("User.LastName")%>
    </div>
</div>

and a jQuery selector that is supposed to detect when the input gets focus and highlight the parent:

    $("input").focus(function() {
    //watching for an event where an input form comes into focus
        $(this)
    .parent()
        .addClass("curFocus")
    .children("div")
        .toggle();
    });

If i paste this code into firebug's console - things work as planned. However, i'm running this from a 'RenderPartial' .net mvc page. Other jQuery code sitting within the same $(document).ready(function() { block work correctly.

The form uses html helpers to generate the inputs which might complicate the process somewhat - but even so... i'm seeing correct behavior when that code's in console but not in a 'real-time' page.

How do i troubleshoot this?

+1  A: 

When you're rendering a partial, the $("input") selector doesn't find the element to rig this up to, because it isn't there yet. If you change it to a live event, it'll work on elements added after document.ready executes.

To fix it, use .live() like this:

$("input").live('focus', function() {
  $(this).parent().addClass("curFocus").children("div").toggle();
});

Note: requires jQuery 1.4.1+

Nick Craver
RenderPartial happens server side, so all the inputs should be there when `$(document).ready()` fires.
Charlino
@Charlino - Not if he's loading it via ajax, which is usually the case, at least in most stuff I see or do :)
Nick Craver