2015-12-15 26 views
0

我想更改下拉按鈕的選定值。有與類=「凡」一個div幾下拉菜單,我想一個括號追加到第一個下拉和倒數第二個下拉
按鈕調用此函數:在下拉菜單中更改所選文字?

//add parenthesis to the first child, and to the second to last child 
    function addParens(){ 
     var len = $(".WHERE").children('div > select').length; 
     len -= 1; 

     var firstDropdown = $('.WHERE').children().first(); //the first child 
     var lastDropdown = $('.WHERE').children().eq(len); //the second to last child 
//attempting here to append left parenthesis to the first dropdown 
      var text = firstDropdown.val(); //the old selected option 
      text = '(' + text; //new text with left parenthesis 
      console.log(text); //prints out correctly 
      firstDropdown.text(text); //tried ,doesn't work 
      var firstId = firstDropdown.attr('id'); //grab id firstDropdown 
      $('#'+firstId).val(text); //doesn't work by grabbing id first 
      firstDropdown.val(text); //also tried this, doesn't work 




    } 

之後,如果我打印firstDropwdown.val()它打印爲空,並且下拉列表沒有任何選擇。 這裏是什麼樣的下拉列表中的一個看起來像一個樣本,它是動態創建

+2

喜歡這個? http://jsfiddle.net/27nskcf5/ – teynon

+0

是的!這是有效的,謝謝 – stickler

回答

0

function addParens() { 
 
    var len = $(".WHERE").children('div > select').length; 
 
    len -= 1; 
 

 
    var children = $('.WHERE').children(); 
 
    var firstDropdown = children.first().find("option:selected"); //the first child 
 
    var lastDropdown = children.eq(len).find("option:selected"); //the second to last child 
 
    firstDropdown.text('(' + firstDropdown.text() + ')'); 
 
    lastDropdown.text('(' + lastDropdown.text() + ')'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="WHERE"> 
 
    <select> 
 
    <option></option> 
 
    <option>Article.Author</option> 
 
    <option>Article.Editor</option> 
 
    <option>Article.Publisher</option> 
 
    <option>Article.Title</option> 
 
    <option>Article.BookTitle</option> 
 
    <option>Article.Year</option> 
 
    </select> 
 
    <select> 
 
    <option></option> 
 
    <option>Article.Author</option> 
 
    <option>Article.Editor</option> 
 
    <option>Article.Publisher</option> 
 
    <option>Article.Title</option> 
 
    <option>Article.BookTitle</option> 
 
    <option>Article.Year</option> 
 
    </select> 
 
    <select> 
 
    <option></option> 
 
    <option>Article.Author</option> 
 
    <option>Article.Editor</option> 
 
    <option>Article.Publisher</option> 
 
    <option>Article.Title</option> 
 
    <option>Article.BookTitle</option> 
 
    <option>Article.Year</option> 
 
    </select> 
 
    <select> 
 
    <option></option> 
 
    <option>Article.Author</option> 
 
    <option>Article.Editor</option> 
 
    <option>Article.Publisher</option> 
 
    <option>Article.Title</option> 
 
    <option>Article.BookTitle</option> 
 
    <option>Article.Year</option> 
 
    </select> 
 
</div> 
 
<button onClick="addParens();"> 
 
DO IT 
 
</button>

相關問題