开发者

appending / removing / replacing

开发者 https://www.devze.com 2023-03-02 13:06 出处:网络
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:

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

currentValue.replace(uID,"");

To

currentValue = currentValue.replace(uID,"");

Also for optimizing your code you may use jquery objects chainability.

$(this).removeClass("addable").addClass("removable").appendTo("#selections ul");


Instead of trying to update the hidden input every time a selection is made, why not have an onsubmit handler take care of this work for you?

<form onsubmit="GetSelectedListIds()">

And:

function GetSelectedListIds() {
  var ids = [];
  $("li", "#selections").each(function() {
    ids[ids.length] = $(this).attr("id");
  });
  $("input#edit-r").val(ids.join());
}

In this manner, you don't have to worry about your hidden element staying in sync with the selected items.

0

精彩评论

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

关注公众号