开发者

Converting a list into a select with jquery

I'm trying to convert the following list into a select list so it can be submitted via a form - the element within the lists will become the value of each option:

<ul class="selected connected-list ui-sortable" style="height: 279px;">
<开发者_如何学Python;li class="ui-helper-hidden-accessible" style=""></li>
<li title="Owner Name 1 - " class="ui-state-default ui-element ui-draggable" style="display: block; position: relative; top: 0px; left: 0px;"><span class="ui-icon-arrowthick-2-n-s ui-icon"></span>Owner Name 1 - <em class="thenumber">4.4796E+11</em><a class="action" href="#"><span class="ui-corner-all ui-icon ui-icon-minus"></span></a></li>
<li title="David Moffat - " class="ui-state-default ui-element" style="display: block; position: relative; top: 0px; left: 0px;"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>David Moffat - <em class="thenumber">07730423005</em><a class="action" href="#"><span class="ui-corner-all ui-icon ui-icon-minus"></span></a></li>
</ul>

This should convert to the following format:

<select style="display:none" class="selectoption" name="p_num[]" multiple="multiple">
<option value="">4.4796E+11</option>
<option value="">07730423007</option>
</select>

I have tried the following jquery code, but after many hours I'm pulling my hair out:

$('a.sendform').click(function(){
 $('ul.selected').each(function() {
  var $select = $('<select />');

  $(this).find('li').each(function() {
   var $option = $('<option />');
   $option.attr('value', $(this).('em')).html($(this).html());
   $select.append($option);
  });
  $(this).replaceWith($select);
 });
});

Any help might save my remaining hair.

Many thanks

David


$('a.sendform').click(function() {
    var $select = $('<select style="display:none" class="selectoption" name="p_num[]" multiple="multiple" />');
    $('li em').each(function(i, el) {
        $select.append('<option value="">' + $(el).text() + '</option>');
    });
    $(this).replaceWith($select);
    return false;
});

As the select is hidden (display:none) you might not see it actually replacing the anchor tag.


This is a perfect use for the 'map' method.

$(".connected-list > li:has(em)").map(function(index,elem){
    return $("<option/>").attr("value","").html($("em", $(elem)).html());
}).appendTo('.selectoption');

jQuery Map API Page

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜