2011-11-28 21 views
0

this script找到多個選擇框的標籤與jQuery

我想達到這個網站:

City 
Paris 
Bern 
Sex 
Male 
Female 

但隨着我的腳本,標籤相互取代的變化。我怎樣才能得到上面的HTML? 在此先感謝

腳本:

$("select").change(function() { 
    var str = ""; 
    var id = $(this).attr('id'); 
    var label = '<li><b>'+$("label[for='" + id + "']").text()+'</b> </li>'; 
    $("select option:selected").each(function() { 
     str += '<li>'+$(this).text()+'</li>'; 
     }); 
    $("ul").html(label + str); 
}) 
.trigger('change'); 

HTML:

<label for="sex">sex</label> 
<select id="sex" multiple="multiple"> 
    <option>Male</option> 
    <option>Female</option> 
</select> 
<label for="city">City</label> 
<select id="city" multiple="multiple"> 
    <option>Paris</option> 
    <option>Bern</option> 
</select> 
<ul></ul> 
+0

請張貼的問題在您的代碼。 –

回答

2

試試這個小提琴:http://jsfiddle.net/XWr4W/2/

$("select").change(function() { 
    var str = ""; 

    // Only loop through selects which have selected elements 
    $("select:has(:selected)").each(function() { 

     var id = $(this).attr('id'); 
     str += '<li><b>' + $("label[for='" + id + "']").text() + '</b> </li>'; 

     // Loop through the selected elements of this SELECT 
     $(this).find("option:selected").each(function() { 
      str += '<li>' + $(this).text() + '</li>'; 
     }); 
    }); 
    $("ul").html(str); 
}).trigger('change');