将下拉列表中的选定选项分配给jquery中的变量

时间:2017-05-20 16:53:36

标签: javascript jquery

我想从下拉列表中选择所选的选项成为selectedSubject变量,但我遇到了问题,我的代码有一半工作......

selectedSubject = $('select#subject-options').val();

但是当选择不同的选项时它不会改变?? 并且需要改变我正在创造的游戏

HTML:

<p>Subjects</p>
<select id="subject-options" name="subject-options">
  <option selected disabled >Please Choose</option>
  <option id="BBT" value="$BBT">Big Bang Theory</option>
  <option value="$LOTR">Lord Of The Rings</option>
  <option value="$EPL">EPL Football Teams</option>
  <option value="$ASIA">Asian Countries</option>`
</select>

Jquery的:

const $BBT = ['sheldon','leanord','spock','cheescake``factory','howard','raj','star` `trek','penny','amy','bernadette','physics','laundry','halo` `night','dumplings', 'brisket','nasa','string theory','dark matter',` `'comiccon'];

let selectedSubject = $BBT;
selectedSubject = selectedSubject[Math.floor(Math.random() * selectedSubject.length)];

我遇到过7个不同类似的问题,找不到任何对我有帮助的问题,所以如果有人可以直接帮助我,或者将我引导到另一个已经回答的问题,那将帮助我解决问题。

2 个答案:

答案 0 :(得分:0)

在jQuery选择器中,您可以获取select对象本身。您需要option对象,尤其是selected对象。

selectedSubject = $('select#subject-options option:selected').val();

答案 1 :(得分:0)

每次更改选择时,都必须向#subject-options添加事件处理程序以更新selectedSubject变量。

$('#subject-options').on('change', function() {
    selectedSubject = $('#subject-options option:checked').val();
});

JS Bin