在下拉列表中更改所选文本?

时间:2015-12-15 05:29:08

标签: javascript jquery drop-down-menu

我想在按下按钮时更改下拉列表的选定值。在class ='。WHHERE'的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()它会打印null,并且下拉列表中没有选择任何内容。 下面是一个下拉列表的示例,它是动态创建的

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;