Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery check if li with id=x exists in ul already

I have many UL with li. Different UL will have li with the same id:

<ul>
 <li id='1'>this</li>
 <li id='2'>that</li>
</ul>

<ul>
 <li id='1'>this</li>
</ul>

The user can drag li from on list to the other but only if the li with the same id does not exist. So far I have this:

$(".container").droppable({
        drop: function (event, ui) {
            var a = $(this).find("li").attr("id", $(ui.draggable).attr('id'));
            if (a.length == 0) {
                $.ajax({
                    ...
                });
            }                
        }
    });

However when I drop the draggable it changes the id of all li to the value of the dropped li.

Any guidance would be great. Thanks.

like image 552
abarr Avatar asked Feb 25 '23 12:02

abarr


2 Answers

IDs cannot start with numbers and must be unique. For non-unique identifiers, use classes.

You can check to see if an element exists like this:

if($('#myDIV').length) {

}
like image 195
Diodeus - James MacFarlane Avatar answered Mar 05 '23 23:03

Diodeus - James MacFarlane


By using attr(), you're actually setting the id attribute of any elements matched by your find() call. You should use find on the ID you're matching against.

$(".container").droppable({
    drop: function (event, ui) {
        var a = $(this).find("#" + $(ui.draggable).attr('id'));
        if (a.length === 0) {
            $.ajax({
                ...
            });
        }                
    }
});

Also, as @Diodeus mentions, IDs should not start with a number. They should also be unique document-wide, so if you need duplicate/expect IDs, I'd recommend using a different attribute, such as an HTML5 data attribute: http://ejohn.org/blog/html-5-data-attributes/

like image 29
Gary Chambers Avatar answered Mar 06 '23 00:03

Gary Chambers