javascriptjqueryhtml

How can i get Ids from li tags using jQuery?


Here is html code :

<ul id="sortable">
    <li id="attachments[183]"></li>
    <li id="attachments[196]"></li>
    <li id="attachments[145]"></li>
    <li id="attachments[545]"></li>
</ul>

Here is JavaScript/jQuery code :

var query = {
    'action'  : 'save-attachment-order',
    'nonce'   : '8cb16e3927',
    'post_id' :  89,
}

I want to get li IDs and make it this var like this

var query = {
    'action'  : 'save-attachment-order',
    'nonce'   : '8cb16e3927',
    'post_id' :  89,
    'attachments[183]' : 2,
    'attachments[196]' : 3,
    'attachments[145]' : 1,
    'attachments[545]' : 4
}

Solution

  • Starting with this object:

    var query = {
        'action'  : 'save-attachment-order',
        'nonce'   : '8cb16e3927',
        'post_id' :  89,
    }
    

    You can add the ids as new properties with this:

    $("#sortable li").each(function(){
        query[this.id] = 0; // not sure where you're getting the values from!
    });
    

    Now that you explained that the values are supposed to represent the order, you may want to use this instead (assuming jQuery UI):

    var order = $( "#sortable" ).sortable( "toArray" );
    for(var i=0; i<order.length; i++) {
        query[order[i]] = i+1;
    }
    

    Alnitak's answer should also work, as the the list items will be in order anyway.