Sandra Schlichting
Sandra Schlichting

Reputation: 26046

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 unchecked, and submit is clicked a 'x' should disappear, like to does now.

The problem is that the 'x' doesn't appear again, if the checkbox is checked, and submit is clicked.

This is my code

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


<form action="" method="post">
<input id="element" signed" type="checkbox" checked>
<label for="element">x</label>
<button type="submit">Submit</button>
</form>

Any idea what's wrong?

Upvotes: 1

Views: 91

Answers (4)

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10646

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();
    }        
    return false;
});

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

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();
    }        
    return false;
});

Here's a live example.

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100381

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

Upvotes: 1

jhurshman
jhurshman

Reputation: 6067

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.

Upvotes: 2

Related Questions