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

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.

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

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

Related

What is the difference between xxx.value and xxx.options[xxx.selectedIndex].value to get the value of selected option with JavaScript?

After some research and testing, I figured out both methods produce the same result. So I was just wondering what the difference is between:
function buildUrl() {
compType = document.querySelector('[name = "c-type"]');
compTypeValue = compType.value;
}
and
function buildUrl() {
compType = document.querySelector('[name = "c-type"]');
compTypeValue = compType.options[compType.selectedIndex].value;
}
<form id="custom-drop">
<select name="c-type" id="compressor-type">
<option value="screw">Screw</option>
<option value="scroll">Sroll</option>
<option value="centrifugal">Centrifugal</option>
<option value="piston">Piston</option>
</select>
</form>
I did read questions (this and this) related to this topic but I couldn't find any explanation for their differences.
The select element keeps track on as well the value of the currently selected item and of the index of the selected items.
In your first example you access value of the currently selected option.
In the second one you get the whole option element takeing the one at the index-postion that is selected.
By accessing its value-member you then return its value.
By this you get the same result.
However i would call the second approach hacky and not consider doing it.

JS keep to selects in sync (no jquery)

I have two SELECT elements on a page and what I need to do is if the first one is changed, have the second contain all the OPTIONS from the first except the one that is currently selected in the first.
They start off with identical options and I can disable the second until the first is selected if needed. So, if I have:
...
<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>
<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>
...
...and Two is selected in the first, then it should be removed from the second. Then if Three is selected in the first, the second should have everything in listed in the first (including Two again) except Three. The first ones options never change and the second should always have everything in the first except the currently selected option. Any ideas on how best to accomplish something like this?
I cannot bring JQuery into the mix for this, so please no Jquery specific answers. Beyond that open to pretty much anything. I can get the initial value selected in the first removed from the second, but am not sure how to handle changes from there.
TIA!
If disabling the options in selectTwo is fine, you might do something like this. If not, you might "hide" the matching option with a display:none class and use classList.add and classList.remove to hide and show rather than disable and enable.
Both the hide and disable methods here result in the possibility that the item to remove is the once currently selected in selectTwo. Neither strategy is great in that situation. If you must avoid it, you might either set the value of selectTwo to a "good" one or alternatively, delete the children of selectTwo and clone the non-selected children of selectOne and add those to selectTwo.
If you want an example of the remove/clone strategy let me know and I will post that.
function selectClick(event) {
var that = document.querySelector("#selectTwo");
var thatOptions = that.querySelectorAll("option");
for (var i = 0; i < thatOptions.length; i++) {
thatOptions[i].disabled = (thatOptions[i].value === this.value);
}
}
document.querySelector("#selectOne").addEventListener("change", selectClick);
<select id="selectOne">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="selectTwo">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

HTML Select Option Value Not Updating

I have a HTML form with the following select element in it:
<select class="form-control" onchange="$('form#filter').submit()" id="sort" name="sort">
<option value="0" selected="selected">A - Z</option>
<option value="1">Z - A</option>
</select>
The issue is that when I select a different option, the HTML doesn't update and set the option I chose as the selected option.
I have absolutely no idea why it isn't updating and I've been at it for hours now.
This is the function that is bound to the submit event on the form in case you need it:
$("form#filter").on("submit", function(evt)
{
var form = $(this);
var target = $("div#bands");
var url = form.attr("action") + "/" + form.find('option[selected]').val();
console.log(url);
$.get(url).done(function(data)
{
target.html(data);
});
evt.preventDefault();
});
Change
form.find("option[selected]").val()
to
form.find("option:selected").val()
or:
form.find("select").val()
or:
$("#sort").val()
The selector option[selected] doesn't find the option that's currently selected, it finds the option that has the selected attribute in the DOM (this is normally the one with the selected attribute in the HTML, although it's possible to change it using Javascript).
The accepted answer is incorrect. Here is a correct solution (tested on latest JQuery and Bootstrap at time of writing):
$("#mySelect").find("option:selected").val();
Thanks to Barmar for the inspiration, though only 1 of the 4 suggestions works, and only by accident. But I adapted that to log out the correct value attribute for the currently selected option. (The selected state of the initial option does not update when using the dropdown, see Chris O'Kelly's comment.)

Selected using option ID

<select id="editSkillList">
<option id="0">Select</option>
<option id="8">text1</option>
<option id="5">text2</option>
<option id="4">text3</option>
</select><br><br>
Javascript code
document.getElementById("editSkillList").selectedIndex="2";
But i want set selected using option id.Is it posible? then please help me
You can just set the selects value to the text you get from the option after targeting the ID
document.getElementById("editSkillList").value = document.getElementById('4').innerText;
FIDDLE
EDIT:
If the options have a value, you just set the selects value to one of the options value
document.getElementById("editSkillList").value = document.getElementById('4').value;
You can do:
document.getElementById('5').selected = true;
Replace '5' with the id of the option you need to select.
you can select your option using below code.
Javascript
document.getElementById("editSkillList").value = document.getElementById('4').value;
or you can use this code also.
var editSkillList = document.getElementById("editSkillList");
editSkillList.options[editSkillList.selectedIndex].value;
i hope it will help you.

Select Event from Drop Down Menu - Javascript Only

I have tried this a hundred ways, need some help getting going. I did look at other people's questions and answers but have been unable to use any of them and get them to work. I have a drop down menu. I need to create an event, changing the color in a div for each of the options in the drop down menu. Code is below, I need to use Javascript only not JQuery.
Here is the HTML for the "menu"
<select name="colorBlog" id="colors">
<option value = "Red">Red</option>
<option value = "Blue">Blue</option>
<option value = "Green">Green</option>
<option value = "Yellow">Yellow</option>
<option value = "Pink">Pink</option>
</select>
Try
function changecolor() {
document.getElementById('mydiv').style.color = colors.value
}
var colors = document.getElementById('colors');
colors.addEventListener('change', changecolor);
changecolor();
Demo: Fiddle

Categories