madmatuk
madmatuk

Reputation: 127

assign array values to elements on page

I'm still a little new to jQuery and need a little help.

I am using a drag and drop script as below.

$(document).ready(function() {
    $(function() {

        $("#contentLeft ul").sortable({
            opacity: 0.6,
            cursor: 'move',
            update: function() {

                var order = $(this).sortable("serialize") + '&action=updateRecordsListings';

                $.post("updateDB.php", order, function(theResponse) {

                    $("#contentRight").html(theResponse);

                });

            }

        });

    });

}); 

theResponse contains a dynamic array like below once the drag and drop is complete and the php server side script has parsed.

Array
(
    [0] => 3
    [1] => 4
    [2] => 1
    [3] => 2
)

What i need to be able to do is once i have the response - rename the div ids of the corresponding divs, so the top one will get questionOrder_0, the next questionOrder1 the next questionOrder2 so on and so on.

The divs on page load are created dynamically like below.

<div id="questionOrder_0" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_1" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_2" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_3" class="questionHolder"> ...some stuff here ... </div>

But once i have dragged and dropped it would like this if i move say div #questionOrder3 to the top :

<div id="questionOrder_3" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_0" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_1" class="questionHolder"> ...some stuff here ... </div>
<div id="questionOrder_2" class="questionHolder"> ...some stuff here ... </div>

The database that the php script updates is altered accordingly but i need to alter the div ids live once a drop has taken place.

I hope this makes sense .

Upvotes: 0

Views: 90

Answers (2)

Jack
Jack

Reputation: 8941

Here's a simple example that will help you get on your way. http://jsfiddle.net/LcK8G/5/

var a = ['a','b','c','d'];
//loop through each div, change selector for your needs
$('div').each(function(i,el){
    $el = $(el); //grab this iterations element and make a jQuery object out of it
    $el.attr('id',a[i]); //change the elements id based on this iterations index
    //this just displays the id for you to see how it is working, would be removed later
    $el.text($el.attr('id')); /=
});

Upvotes: 1

Shawn Khameneh
Shawn Khameneh

Reputation: 472

I don't exactly understand why you wish to manipulate the ID's.

You can encounter conflicts if any two elements are assigned the same ID at any given time.

It would be best to do some sorting server-side or in place of the serialize in JS.

Upvotes: 0

Related Questions