Skip to content Skip to sidebar Skip to footer

Want To Add Element. What's Wrong?

In this JSfiddle have I a checkbox, a label and a submit button. When the checkbox is checked, and submit is clicked a 'x' should appear, like to does now. When the checkbox is unc

Solution 1:

Well, if you use show() and hide() instead of add() and detach(), it works.

But I'm not certain if that approach addresses what you are trying to achieve.

Solution 2:

The x doesn't appear again because you are not adding the detached element, you are trying to add a new element without a text.

$("label").add();

See the correct use of add.

Also, you are detaching and not saving the reference to attach it back. See an example of detach on jQuery docs

Solution 3:

When you detach the label, it's no longer in the DOM, so $('label') no longer works. You'll have to store the node somewhere whilst it's not in the DOM.

Also add is not the correct function to add a node into the DOM.

var $label = $("label");
$('form').submit(function() {
    if( $("input[type=checkbox]").is(':checked')){
        $("input[type=checkbox]").after($label);
    }
    else {   
        $label.detach();
    }        
    returnfalse;
});

Here's a live example.

Solution 4:

After detaching the label is no longer part of the DOM, so you can no longer select it using $('label'), also add() doesnt do what you think it does, you might be looking for after()?

Working fiddle:

xLabel = $("label");
$('form').submit(function() {
    if( $("input[type=checkbox]").is(':checked')){
        $("#element").after(xLabel);
    }else{   
        $("label").detach();
    }        
    returnfalse;
});

Post a Comment for "Want To Add Element. What's Wrong?"