tags:

views:

35

answers:

2

I am creating a form in jQuery. When the page loads I'm hiding all textboxes and trying to replace them with a span.

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span").hide();
});

This goes through each text input places a span after the textbox with a id the same as the textbox but "span_" appened to the start..

Now I want to apply hover on the spans: $("span").hover

I guess i could do it inside the each or try apply it afterwards (when all have been created) but im not sure how to go about it to get it to work

A: 

Since you're just hiding them and not detaching them, this should do the trick:

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span>").hide();
});
$("form input:text+span").hover(...);

Another alternative is using $(this).next().hover() inside the loop, after adding the element, like this:

$("form input:text").each(function(index) {
    $(this).after("<span id='Span_" + $(this).attr("id") + "'>" + $(this).val() + "</span>").hide().next().hover(...);
});

That is probably a better solution, since you get to bind the events individually. It adds unnecessary computations if you don't need to bind individually though.

You
+3  A: 

You can change it around a bit like this:

$("form input:text").each(function(index) {
  $("<span />", { "id": 'Span_' + this.id, text: $(this).val() })
    .insertAfter(this)
    .hover(function() {
      //do something
    });
  $(this).hide();
});

This uses $(html, props) to create the object, and instead of .after() uses .insertAfter(), that way your chain refers to the created element, so you can do whatever you want to it directly.

Nick Craver