Reputation: 26046
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
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()
?
xLabel = $("label");
$('form').submit(function() {
if( $("input[type=checkbox]").is(':checked')){
$("#element").after(xLabel);
}else{
$("label").detach();
}
return false;
});
Upvotes: 1
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;
});
Upvotes: 1
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
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