views:

67

answers:

2

Hi,

let's say I have this set of HTML-markup and CSS

#CSS

.inputhelp_text { background: #000; color: #fff; }
.nodisplay { display: none; }

<input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname">Write in your firstname</span>

<input class="inputhelp" id="lastname" /><span class="inputhelp_text nodisplay" id="help_lastname">Write in your lastname</span>

Using jQuery, I need to bind a function to all input fields (I guess using jQuery's EACH function) so that when I click the input field, it should switch the class of each span to only "inputhelp_text". I've gotten this to work in two separate functions for each field, but since I have alot of fields, I know there's a better way to solve it.

Any suggestions?

A: 

You can use the each function:

$("input").each(function() {
  // this points to the input DOM element
  // $(this) is the jQuery wrapped element
});

For example you could have:

$(this).removeClass("inputhelp");
$(this).addClass("inputhelp_text");

inside the callback.

kgiannakakis
Could this work as well?? To select all inputs with class "inputhelp" ?$('input[class=inputhelp]').bind('focus',function() { // do something }
bakkelun
Yes, but $("input.inputhelp") or $(".inputhelp") are more simple selectors that do the same thing.
kgiannakakis
Please remember that shorter (more non-spesific) triggers makes the search for it inside the DOM slower. Much like xpath queries; specifying a longer more spesific path speeds up the query.
bakkelun
+2  A: 

You want to bind handlers to the blur() and focus() events:

$(".inputhelp").focus(function() {
  $("span.inputhelp_text:visible").addClass("nodisplay");
  $(this).next("span.inputhelp_text").removeClass("nodisplay");
}).blur(function() {
  $("span.inputhelp_text").addClass("nodisplay");
});

Normally I'd recommend using jQuery effects like hide() and show() but these only really work with block level elements. <span> are inline so this won't work.

cletus
Did not work like it should, for some reason.
bakkelun
@bakkelun details would undoubtedly be useful
cletus
firebug didn't report anything wrong and I can't debug that
bakkelun