开发者

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?


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.


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


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.


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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜