tags:

views:

78

answers:

2

I have a set of divs that represent a set of fields. What I would like to acheive is that on click of a text box you can get the div with the class "hint" which is within the same div.

For example if I click "txtUsername" i should get "usernameHint"

This is the html

  <div class="formfield">
            <label class="desc" id="lblUsername" runat="server">Username</label>
            <input type="text"  id="txtUsername" runat="server" class="field text medium" />
            <div id="usernameHint" class="hint" runat="server"></div>    
            <div id="usernameError" runat="server"></div> 
  </div>

  <div class="formfield">
        <label class="desc" id="lblPassword" runat="server">Password</label>
        <input type="password" id="txtPassword" runat="server" class="field text medium" /> 
        <div id="passwordHint" class="hint" runat="server"></div>    
        <div id="passwordError" runat="server"></div>  
  </div>

Any ideas?

+5  A: 
$('#txtUsername').click(function() {
    $(this).parent().find('.hint').text('Must be between 5 and 12 characters in length');
});

That selects the parent of the textbox, which is your <div class="formfield">, then finds the element with class hint inside it, thus eliminating the need for an ID and a more complex way to get the contained hint div.

karim79
A: 
var hints = (function () {
   /**
    * @var Default selector to display hints for
    */
   var defaultSelector = 'input[type=text]',
   /**
    * This object contains all the public methods.
    */
       handlers = {
         /**
          * Apply fn on the hint-element belonging to the context element
          */
          action: function (fn) {
             var hint = $(this).parent().find('.hint');
             if(hint) {
                hint[fn]();
             }
         },
        /**
         * Show the hint of the element that received focus
         */
         focusListener: function () {
             handlers.action.call(this, 'show');
         },
        /**
         * Hide the hint of the element that lost focus
         */
         blurListener: function () {
             handlers.action.call(this, 'hide');
         },
         /**
          * Initialize listeners for the elements matched by selector
          * @param string [specificSelector] Override the default selector
          * with another one
          */
         init: function (specificSelector) {
            var selector = specificSelector || defaultSelector;
            $(selector).focus(handlers.focusListener);
            $(selector).blur(handlers.blurListener);
         }
      };
   return handlers;
}());

This object can be called like so to add the hint functionality:

hints.init(); // Add focus and blur listeners on all input-text elements

// Add focus and blur listeners on all input-text and radio elements
hints.init('input[type=text], input[type=radio]');
PatrikAkerstrand