append() is working, remove() is not
I am making a user registration form, in which the user must make one or more category selections via checkbox inputs. There are a lot of categories to choose from (150 in fact), so rather than display them all on the form outright, I have a link that opens up a
fancybox popup with all the checkboxes in it.
Since all the checkboxes are in the fancybox popup, I want to make an <ol> on the form that gets appended with what the user selected, so they can see what they selected after they close the fancybox. Also, if they uncheck a box, I want that <li> to be removed from the <ol>.
Here is my Javascript code:
- $("input:checkbox").click(function(){
- //alert($("label[for="+this.value+"]").html());
- var li_text = $("label[for="+this.value+"]").html();
- if($(this+":checked")){
- $("ol#selected_types").append("<li>"+li_text+"</li>");
- } else {
- $("li").remove(":contains('"+li_text+"')");
- }
- });
And here is a sample of the html (a sample since there are actually 150 checkboxes):
<ul>
<li>
<input name="law_category" value="1" id="1" type="checkbox" />
<label class="list_checkbox" for="1">Administrative Law</label>
</li>
<li>
<input name="law_category" value="2" id="2" type="checkbox" />
<label class="list_checkbox" for="2">Admiralty & Maritime</label>
</li>
- </ul>
- <ol id="selected_types"></ol>
The problem is that the append() works, so <li>s get added to the <ol> with no problem. In fact, even when I UNcheck a box, it adds another <li> to the <ol>.
However, the remove() is not working at all. I think the problem is that the ELSE conditional doesn't necessarily mean the box is unchecked (which I assumed would be the opposite of my IF conditional). I've tested the code within the ELSE by itself via a dummy <a> and it removes the <li> just fine.
So, how can I write a conditional that checks if a checkbox has just been unchecked?