开发者

Populating <select> dropdown with one array

开发者 https://www.devze.com 2023-02-04 10:42 出处:网络
I have a list of over 100 colors in seperate <td>s. Each <td> has a unique ID. I would like to use jQuery to find the ID\'s of every td and put it in an array. Then I would like to use tha

I have a list of over 100 colors in seperate <td>s. Each <td> has a unique ID. I would like to use jQuery to find the ID's of every td and put it in an array. Then I would like to use that array and create something similar to the following:

<select>
    <option value="array[0]"> array[0]</option>
    <option value="array[1]"> array[1]</option>
    ...
</select>`

Every example I've looked at so far requires the coder to manually type out the array. I'm hoping t开发者_如何学Goo find something more efficient.


If you need the array just for populating the drop down then you can bypass creating array. Try this:

<table id="colorsTable">
    <tr>
        <td>...</td>
    </tr>
    .
    .
    .
    .
</table>

<select id="colorsList" name="colorsList">
    <option value="array[0]"> array[0]</option>     
    <option value="array[1]"> array[1]</option>
</select>
<script type="text/javascript">
    function populateDropDown()
    {
        var colorsList = $("#colorsList");
        $("#colorsTable td").each
        (
            function()
            {
                colorsList.append($("<option/>").val($(this).text()));
            }
        );
    }
</script>


You could do something like this:

var $select = $('<select>');
$('#tableID td[id]').each(function(idx){
    $select.append('<option value="' + this.id + '"> ' + this.id + '</option>');
});
$select.appendTo('#someElement');


$("td").get() 

gets you an array with all the matched elements. Then you can just traverse, for every element of array you build up your options string. Something like this:

var s = "";
var elements = $("td").get();
for (var i=0; i<elements.length; i++) {
    var el = elements[i];
    s+='<option value="'+el.id+'">'+el.id+'</option>'; 
}

If you have other tds on the page, do something like $("element#that-is-parent-to-needed-tds td");


var cells = $('table tr td');
var sel = $('<select>');

cells.each(function(cell) {
 var opt = document.createElement('option');
 opt.value = cell.id;
 opt.innerHTML = cell.id;
 sel.append(opt);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消