I’m not sure if this is the most optimal way of writing this code, but what I have almost works…
This is what I’m trying to do:
(1) Move the <li></li> element to another div when clicked
(2) Update a hidden input field by either appending or removing the <li id>
Note: I don’t want to replace the value in the hidden input field, but add to it, so that you can wind up with a value of “u40,u56,u98” … etc…
So, when a user clicks on an <li> element with the class of addable, it’s removed from it’s parent <ul> and appended to the <ul> in another div. Additionally, the hidden input field will update with the id of the <li> element. Conversely, if a user clicks on an <li> element with a class of removable, the opposite happens… The <li> is removed from it’s parent <ul> and appended to the other one, and the hidden input field updates by removing the id of the <li> element…
This is what I have so far… It works when you add it, but the hidden input field doesn’t remove the value when you click on the li.removable element.
$('li').click(function() {
var uID = $(this).attr('id')+',';
if($(this).hasClass("addable")) {
$("input#edit-r").val($("input#edit-r").val() + uID);
$(this).removeClass("addable");
$(this).addClass("removable");
$(this).appendTo($("#selections ul"));
} else {
var currentValue = $("input#edit-r").val();
currentValue.replace(uID,"");
$("input#edit-r").val(currentValue);
$(this).removeClass("removable");
$(this).addClass("addable");
$(this).appendTo($(".filtered ul"));
}
});
<div class="filtered">
<ul>
<li id="u40" class="addable">U40</li>
<li id="u56" class="addable">U56</li>
<li id="u98" class="addable">U98</li>
</ul>
</div>
<div id="selections">
<ul>
</ul>
</div>
<input type="hidden" id="edit-r" value="" />
change
To
Also for optimizing your code you may use jquery objects chainability.