简体   繁体   中英

Assigning a selected option from a dropdown to a variable in jquery

I want to assign the chosen option from the dropdown to become the selectedSubject variable but am having problems with it, I had code which half worked...

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

But when a different option is selected it doesn't change?? And need it change for the game I am creating

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)];

I have been through 7 different questions similar and couldn't find anything that helped me, so if anyone could help me directly or direct me to another question that has been answered that will help me in my troubles.

In your jQuery selector you grab the select object itself. You need the option object and especially the one that is selected .

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

You must add an event handler to #subject-options to update the selectedSubject variable each time you change your selection.

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

JS Bin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM