assigning unique id's to dropped element

hello everyone i'm trying to assign unique id's to dropped elements.When I drag an element from one div tag to another an id is assigned to it,but when i drag that element to another position the id gets changed.I want to keep the id same,even when the same element is dragged multiple times.

// JavaScript Document

 $(document).ready(function () {
var x = null;     
//Make element draggable
$(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit'
});
 var i=1,j=0;
var x1,x2,y1,y2,tmp,tmp2;
$("#droppable").droppable({

  drop: function(e, ui) {

    ui.helper.attr('id',"id"+i);
    //ui.helper.remove();
    tmp=ui.helper.attr('id');
    x = ui.helper.clone().bind("click",'img',function(){
    alert("clicked"+ ui.helper.attr('id') + tmp + tmp2);
    leftpos = ui.offset.left-210;
    toppos= ui.offset.top;
    //document.write("leftpos="+ leftpos);
    //document.write("toppos="+ toppos);

    var cor=window.prompt("Enter coordinates x1,y1");
    //window.location.href="floordata.php?c="+cor;

    });

            x.draggable({
            helper: 'original',
           containment: '#droppable',
            tolerance: 'fit',
        }); 

        x.appendTo('#droppable');
        ui.helper.remove();
        i++;
        }

      });
   });

Answers 1

  • Assuming your divs have no id assigned to them before first dragging, you can simply check for the id, and don't re-assign if one exists. Something like this should work

    var attr = ui.helper.attr('id');
    
    // check if the id attribute exists, if it doesn't assign id
    if (typeof attr == typeof undefined || attr == false) {
        ui.helper.attr('id',"id"+i);
    }
    

Related Articles