change div id on drop with jquery

760 Views Asked by At

I have a bit of code that lets me drag and drop elements. The problem is that i don't know how to change the id of the element when it's dropped. It needs to stay a list with the right numbers.

<div class="container">     

    <div class="block">
        <div id="draggables">
            <div id="dragbox1" class="stepbox">
                <label>Step 1</label>
                <input type='text' placeholder="Omschrijving" name="textbox1">
            </div>
            <div id="dragbox2" class="stepbox">
                <label>Step 2</label>
                <input type='text' placeholder="Omschrijving" name="textbox2">
            </div>
            <div id="dragbox3" class="stepbox">
                <label>Step 3</label>
                <input type='text' placeholder="Omschrijving" name="textbox3">
            </div>
        </div>
    </div>

</div>

When i drag a div (for example the div with id dragbox1 down under the div with id dragbox3) i want the jquery to rename the div id's so that it stays in the same order from 1,2,3 and not 2,3,1.

I'm thinking it should be sometging like the folowing:

var divClass = /*div class name*/;
var divId = /*static div id name*/;

var checkDivOrder = function(){
        if(/*check for divs with the name of the divClass*/) {
            if (divId === /*static div id name*/) {
            divId = /*divIdName*/ + 1;
        } else {
            divId = /*divIdName*/ + /*previous div id number*/ + 1;
        }
    }
};

//recall function
if(/*div being dropped*/){
    checkDivOrder(/*prev div number + 1*/);
}

Could someone help me with this as my jquery and javascript skills are not that great.

1

There are 1 best solutions below

1
On

According to my understanding you want you div in order top to down like dragbox1,dragbox2,dragbox3 in sequence.

you can do like this.

 $('.stepbox').each(function(ind,obj){
 $(this).prop('id','dragbox'+(ind+1));
});