Want to add an item. What's wrong?

In this, JSfiddle has a checkbox, label, and submit button.

When the box is checked and click Submit, an x ​​will appear, as it is now.

If the box is unchecked and press the "x" button, it will disappear, as it is now.

The problem is that the "x" does not appear again if the checkbox is checked, and click the "Submit" button.

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 is wrong?

+1
source share
4 answers

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

But I'm not sure this approach is about what you are trying to achieve.

+2
source

When you detach shortcut, it is no longer in the DOM, so $('label') no longer works. You will have to store the node somewhere until it is in the DOM.

Also add not a valid function to add node to 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 is a living example.

+1
source

x does not appear again, because you are not adding a separate element, you are trying to add a new element without text.

 $("label").add(); 

See the correct use of add .

In addition, you disconnect and do not save the link to attach it back. See the disconnect example in jQuery docs

+1
source

After detaching, the label is no longer part of the DOM, so you can no longer select it using $('label') , and add() doesn’t do what you think you can do after() ?

Working script:

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

All Articles