Junaid Shah Junaid Shah - 2 months ago 5
HTML Question

Easiest way to access unordered list ids as array in PHP

I have an unordered list; I am using DB ids as list-item ids; After the Submit button pressed, I want all ID's of my list-items to be presented as an Array in PHP. I am new to javascript; there are solutions available but can't really figure out proper solution.
Thanks to all in advance.

Answer

Assuming you got html like this ...

<ul>
   <li id="1">
     item 1
   </li>
   <li id="2">
     item 2
   </li>
</ul>

... you can rebuild it like this (with hidden-tags) ...

<ul>
   <input type="hidden" name="ids[1]" />
   <li id="1">
     item 1
   </li>
   <input type="hidden" name="ids[2]" />
   <li id="2">
     item 2
   </li>
</ul>

.. then in PHP you can access it like this ..

$arrIds = $_REQUEST["ids"];  // array(1, 2)

PS:

I first missed you wanted it in PHP so here still as additional info how to do it in JS:

You can use the following code to get an array of ids fetched from the li-ids:

var ids = [];
$("li").each(function() {
   ids.push(this.id);
});

... or withouth jquery ...

var ids = []
var lis = document.getElementsByTagName("li");
for(var i = 0; i < lis.length; i++ ){
   ids.push(lis[i].id);
}