onlineracoon
onlineracoon

Reputation: 2970

jQuery wrapping div

What I need is to wrap HTML around a current div, this is what I got so far:

HTML:

<input type="text" data-placeholder="username" />

Needs to be rendered as:

<div class="placeholding-input">
  <input type="text" data-placeholder="username" />
  <label>Username</label>
</div>

What I got so far:

$.each($('input[type="text"], input[type="password"], textarea'), function(){
    var input = $(this);
    var container = $('<div />').addclass('placeholding-input');
    input.wrap(container);
    var label = $('<label />').html(input.data('placeholder')).appendTo(container);
});

But that ain't working for some reason, I have no idea why.

Thanks for help :)

Upvotes: 1

Views: 506

Answers (5)

jbabey
jbabey

Reputation: 46647

In addition to the syntax error in addclass, append the label to the div before wrapping the input.

http://jsfiddle.net/Yb9QV/

$.each($('input[type="text"], input[type="password"], textarea'),
       function(){
            var input = $(this);
            var container = $('<div />').addClass('placeholding-input');

            var label = $('<label />')
                .html(input.data('placeholder')).appendTo(container);

            input.wrap(container);
});​

Upvotes: 1

gdoron
gdoron

Reputation: 150253

var container = $('<div />').addclass('placeholding-input');

To:

var container = $('<div />').addClass('placeholding-input');
//                              ^--------------------- upperCase

Full code:

$('input[type="text"], input[type="password"], textarea').each(function() {
    var input = $(this);
    var container = $('<div>').addClass('placeholding-input');
    var label = $('<label>').html(input.data('placeholder'));
    input.wrap(container).after(label);
});​

DEMO

Upvotes: 3

thecodeparadox
thecodeparadox

Reputation: 87073

$.each($('input[type="text"], input[type="password"], textarea'), function(){
    var input = $(this);
    var container = $('<div />').addClass('placeholding-input'); // not addclass
    var label = $('<label />').html(input.data('placeholder'));
    input.wrap(container).after(label);
});

DEMO

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try like below,

$(function() {
    $.each($('input[type="text"], input[type="password"], textarea'), function() {    
        var input = $(this);
        var container = $('<div />').addClass('placeholding-input');
        var label = $('<label />').html(input.data('placeholder'));
        input.wrap(container).after(label);
    });
});

DEMO: http://jsfiddle.net/skram/CsGUv/

Upvotes: 2

onlineracoon
onlineracoon

Reputation: 2970

var input = $(this).wrap((container = $('<div />').addClass('placeholding-input')));
input.after((label = $('<label />').html(input.data('placeholder'))));

Done, thanks for help :)

Upvotes: 1

Related Questions