Dirk Shags
Dirk Shags

Reputation: 13

Add new input and use this without modify HTML

I have only:

<div>
    <textarea id="names"></textarea>
</div>

I can't modify html. I can use only jQuery. Is possible make something like:

<input type="checkbox" id="yes">
<div style="display:none">
   <textarea id="names"></textarea>
</div>

$("#yes").click(function(){
    $("#names").parent().show();
})

Default if page is loaded and ready should be only:

<input type="checkbox" id="yes">

If i checked this then show me div with textarea.

Is possible make without modify HTML? If yes, how?

FIDDLE: http://jsfiddle.net/2ZMQz/

Upvotes: 1

Views: 101

Answers (3)

MMM
MMM

Reputation: 7310

Try the following

$("#names").parent().hide().before('<input type="checkbox" id="yes" />');

You can improve the checkbox functionality by using toggle instead of show

$("#yes").click(function(){
    $("#names").parent().toggle();
})

As the name suggests it will toggle the visibility, so if you deselect the checkbox it hides the content.

http://jsfiddle.net/2ZMQz/7/

Upvotes: 1

binarious
binarious

Reputation: 4588

var checkbox = $('<input type="checkbox">');
var parent   = $('#names').parent().hide().before(checkbox);

checkbox.click(function() {
    parent.toggle();
});

http://jsfiddle.net/2ZMQz/14/

Upvotes: 3

Simon
Simon

Reputation: 381

Yes, you can do this.

$("#names").parent().hide().before('<input type="checkbox" id="yes">');

$("#yes").click(function() {
    if ($(this).is(':checked')) {
        $("#names").parent().show();
    } else {
        $("#names").parent().hide();    
    }});

http://jsfiddle.net/2ZMQz/15/

Upvotes: 0

Related Questions