2012-08-17 134 views
2

檢索選擇我需要檢索的所有頁面上的每個下拉列表中選定的值,並填充這些值的無序列表。當然每個項目都有一個新的li元素。從下拉菜單和填充列表

目前我有這樣的:

$(document).ready(function() { 
    $("select").each(function() { 
     var sel = ""; 
     $(this).find(":selected").each(function() { 
      sel += $(this).text() + " "; 
     }); 
     $(".size-result").text(sel); 
    }); 
});​ 

如何去使用它來創建一個新的li元素,然後插入的文本?

我得到了它這方面的工作,感謝wirey:

$(document).ready(function() { 
    $("select").change(function() { 
     var sel = ""; 
    $(".option-select option:selected").each(function() { 
     sel += $(this).text() + " "; 
    }); 
    $(".result").empty().append(sel); 
    }); 
}); 

有沒有一種方法可以讓我否定每一個下拉列表中的第一項?由於它是「選擇...」或「選擇一個...」的值,我想阻止它顯示,因爲它是選擇中的第一個值。

+1

可以顯示一些HTML嗎? – 2012-08-17 16:15:31

回答

2
$(document).ready(function() { 
    var newLI = ''; 
    $("select option:selected").each(function() {   
      newLI += '<li>' + $(this).text() + "</li>";    
    }); 
    $('ulselector').append(newLI); 
});​ 

編輯:

你可以聽在每個下拉列表中的變化和reupdate列表中的每個變化

$(document).ready(function() {   
    $('select').change(function(){ // <-- bind change event handler to the drop downs 
     var newLI = ''; 
     $("select option:selected").each(function() { // <-- then iterate each time it changes 
       newLI += '<li>' + $(this).text() + "</li>";    
     }); 
     $('ulselector').empty().append(newLI); //<-- empty() to remove old list and update with new list 
    }); 
});​ 

再次編輯:

您可以檢查查看所選值的索引是否爲0 ..如果是則不顯示

$(document).ready(function() { 
    $('select').change(function() { // <-- bind change event handler to the drop downs 
     var newLI = ''; 

     $("select option:selected").each(function() { // <-- then iterate each time it changes 
      if ($(this).index() !== 0) { // <-- only if not default 
       newLI += '<li>' + $(this).text() + "</li>"; 
      }  
      $('ul').empty().append(newLI); //<-- empty() to remove old list and update with new list 
     }); 
    }); 
}); 

http://jsfiddle.net/wirey00/bKWpg/

+0

謝謝!現在我必須弄清楚如何在下拉列表中的選擇更改時更新li列表。任何指針? – 2012-08-17 16:25:49

+0

@AjTroxell我更新我的回答 – 2012-08-17 16:29:39

+0

改變夫婦「不一致後,代碼似乎並沒有工作。就算我不惹它了。非常感謝你們的幫助BTW。 – 2012-08-17 17:08:27

0
$("select option[selected]").each(function(i,e) { 
      $("ul#list").append("<li>"+$(e).val()+"</li>");})​; 
0
var selectedArr = []; 
var $ul = $('<ul />'); 
selectedArr = $("select option[selected=selected]").map(function() { 
    return this.value 
}).get(); 
$.each(selectedArr, function() { 
    $ul.append('<li>' + this.slice(3)); 
}); 
$('body').append($ul); 
0
$("select option[selected]").each(function() { 
     $('<li>', { 
      text: $(this).val() 
     }).appendTo('ul#list'); 
});