Getting the value of a dropdown menu using jQuery - javascript

I have added a little drop down menu to a webpage:
function addDropDownMenu() {
var positionMenu = $(
"<form class='drop_down_menu'>" +
"<select name='roles'>" +
"<option value='notSelected'>Not Selected</option>"+
"<option value='relevant'>Relevant</option>"+
"<option value='notRelevant'>Not Relevant</option>" +
"</select>" +
"</form>");
$('#profile-experience .position').prepend(positionMenu)
}
I am trying to get the value of either Relevant or Not Relevant.
However, when I run this code I keep getting an empty string.
var x = $('.drop_down_menu')[0]
// x is the form
$(x).val()
returns ""
What am I missing? Doing wrong?

You could try this:
var selectedValue = $('.drop_down_menu>select').val();
var selectedValue = $('.drop_down_menu>select').val();
console.log('The selected value is: '+ selectedValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>

$('.drop_down_menu') statement returns a jquery element with the properties and methods corresponding to it, but $('.drop_down_menu')[0] just returns the HTML DOM element.
You have to use value property in order to obtain the value of select element.
console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
Your example does not work because you have to use a selector for select element
var x = $('.drop_down_menu > select')[0]
console.log($(x).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>

var _val = $("[name='roles']").val();
console.log(_val);

Related

Why select option change event can't have this and event.target to get selected value?

In select option change event,why can't we get this or event.target to get selected value instead of writing clumsy code like $( "select option:selected" ) to get selected value ?
Pure JavaScript
If you want a pure JavaScript approach, then use the event.target. To quote the official MDN documentation...
The target property of the Event interface is a reference to the object onto which the event was dispatched. (Source: MDN Web Docs: Event.target.)
Since that gives us the element selected, all we then need is the value attribute, and getting the text display would be nothing more than event.target[event.target.selectedIndex].text...
function getSelectedValue(event) {
console.log("Value: " + event.target.value + "; Display: " + event.target[event.target.selectedIndex].text + ".");
}
<select onchange="getSelectedValue(event)">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
Using the above approach, it would be trivial to update it to add in other attributes of the selection option value, all in pure JavaScript.
jQuery
If you want a jQuery approach, then try using the :selected query term...
$("#selector").on('change', function(){
console.log("Value: " + $(this).val() + "; Display: " + $(this).find('option:selected').text() + ".");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
$("select").on('change', function(){
console.log($(this).val());
console.log($(this).find('option:selected').attr('data-attribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option data-attribute="a">1</option>
<option data-attribute="b">2</option>
<option data-attribute="c">3</option>
<option data-attribute="d">4</option>
</select>
You can't get the selected value, but of course you can get the element and the event.target.
<select onchange="mySelectOnchange(this, event)"></select>
function mySelectOnchange(elm, e) {
// **
}
It exists... take a look at this code for example
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', onSelect_change);
function onSelect_change(domEvent){
// get the selected value :
var selectedValue = domEvent.target[domEvent.target.selectedIndex].value;
// you can also do it using domEvent.target.value but the other solution allows you to get every option's property you want
console.log("Selected: " + selectedValue);
}
<select id="select" name="select">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Hope it helps ;)
PS: have a look on http://www.w3schools.com/jsref/prop_select_selectedindex.asp if you want more examples
The only property that's automatically transferred from the selected option to the <select> element itself is the value, because that's the main purpose of selecting an option from a drop-down menu. Other attributes like data-* are not automatically copied, because it's possible for the <select> to have its own attributes, e.g.
<select id="x" data-name="select">
<option value="1" data-name="option1">1</option>
<option value="2" data-name="option2">2</option>
</select>
It wouldn't make sense for $("#x").data("name") to return the name of the selected option instead of the name of the <select>.
<select onchange="getSelectedValue(this)"></select>
...
function getSelectedValue(select) {
console.log(select.value)
}

Dynamically generated select option dropdown menu using JavaScript

This is the select menu I am going to create. But as you can see there are static data. As I actually have bunch of JSON data passed from backend servlet, so there will be hundreds of items for options. I want something like dynamically generate option menu for my dropdown box.
<select id="brand-select" name="brand">
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="lexus">Lexus</option>
</select>
This is my tryout and it doesn't work:
HTML:
<select id="brand-select" name="brand" onChange="createOptions">
<option value="none"></option>
</select>
JavaScript:
//Asssume I have jsonDataForBrands ready, and it contains 100s items
function createOptions() {
for (var fieldIndex in jsonDataForBrands) {
html += '<option value=' + fieldIndex + '>' + jsonDataForBrands[field].title + '</option>';
}
I figured it out by myself...
HTML:
<select id="brand-select" name="brand">
</select>
JavaScript:
function creatBrandOptions(){
for (var field in jsonDataForBrands) {
$('<option value="'+ jsonDataForBrands[field].name +'">' + jsonDataForBrands[field].title + '</option>').appendTo('#brand-select');
}
}
I did an Ajax call to retrieve JSON data from my servlet and then creatBrandOptions() in the same function BTW...
You beat me to it. Here's a complete simplified example of adding options to a select using jquery:
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<button id="populateMenu" >Populate menu</button>
<select id="mySelect">
</select>
<script>
var optionValues= [[1,"first"],[2,"second"]];
jQuery("#populateMenu").click( function () {
for (var i=0;i<optionValues.length;i++){
jQuery('#mySelect').append(jQuery("<option></option>").val(optionValues[i][0]).text(optionValues[i][1]))
}
});
</script>
</body>
</html>
This example uses jQuery. See if it suits you:
function createOptions( jsonDataForBrands ) {
$('#brand-select option').remove(); // first remove all options
for (var i=0; i<jsonDataForBrands.length; i++)
for (var fieldIndex in jsonDataForBrands) { // then populatem them
$('#brand-select').append($("<option></option>").attr("value", fieldIndex ).text(jsonDataForBrands[field].title) );
}

Changing Selected Option in a Drop Down Menu in Javascript

I have this code and I want to change the selected item,being Million(s), to something other than that. How would I do this?
<td>
<select name='list_" + i + "' id='list'>
<option value='0'>Trillion(s)</option>
<option value='1' selected='selected'>Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
</td>
Here is the lines of code im using to try to change the selected option
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
if(document.getElementById("list_"+counter).innerHTML=="true"){
document.getElementById("c" + counter).value = myObject[key];
counter++;
}else{
if(myObject[key]>=1.0E12){
myObject[key]=myObject[key]/1.0E12;
//document.getElementById("list").value=counter;
//document.getElementById("list").getElementsbyTagName('option')[counter].value=counter;
counter++;
}
document.getElementById("c" + counter).value = myObject[key];
}
}
}
I may have understood your requirement wrong.
If you want to change the selected item then it is just matter of changing "selected" attribute.
Let say I want to change it to Trillion, then this is how the code will look like:
<select name='list_" + i + "' id='list'>
<option value='0' selected='selected'>Trillion(s)</option>
<option value='1' >Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
Now let say you want to change the selected item through pure javascript(NO JQUERY)
Here is full example, the selected item will change when you click button.
Note: It is just a matter of changing the index.
<head>
<title> Changing selected option in drop-down menu in JS</title>
<script type="text/javascript">
function changeSelected(){
document.getElementById("list").selectedIndex = 1;
};
</script>
</head>
<body>
<p> Test string....</p>
<td>
<select name='list_" + i + "' id='list'>
<option value='0' selected='selected'>Trillion(s)</option>
<option value='1' >Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
<button onclick="changeSelected()">Try It</button>
</td>
</body>

How to get selected value from select tag using javascript and go to another page using that value

I have a select tag where it contains some values, as shown below:
<select id="menu" SIZE=6 onChange="go()">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Now i am using below script for this, where it get the selected value from the drop down,
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
// here i need to make a specific link using this selected drop down value
}
</script>
I just need to know how can i make use of this selected value and go to specific link like
window.location.href='getCityDetails.jsp?c=sv'; // this is not working properly
Can anyone suggest me best solution for this.
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
window.location.href='getCityDetails.jsp?c=' + sv;
}
</script>
Hope it helps you
HTML :
<select id="menu" SIZE=6 onChange="go(this.value)">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Javascript :
function go(desination){
if (destination != ''){
window.location.href='getCityDetails.jsp?c=' + desination;
}
}
you need to concatenate the string properly. try this:
window.location.href='getCityDetails.jsp?c=' + sv;
-- You can use--
var TaskType = document.form1.SelTaskType.value;
-- TaskType will display selected option from below
<select id="SelTaskType" name="SelTaskType" >
<option selected>-- select --</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>

Javascript Get Values from Multiple Select Option Box

This one is driving me nuts. It’s got to be something simple and stupid that I am overlooking.
I have a multiple select box in a form. I am just trying to get the values that are selected. In my loop, if I use alert then I have no problem. As soon as try to concatenate the values I get the error ‘SelBranch[...].selected' is null or not an object
<form name="InventoryList" method="post" action="InventoryList.asp">
<select name="SelBranch" class="bnotes" size="5" multiple="multiple">
<option value="All">All</option>
<option value="001 Renton">001 Renton</option>
<option value="002 Spokane">002 Spokane</option>
<option value="003 Missoula">003 Missoula</option>
<option value="004 Chehalis">004 Chehalis</option>
<option value="005 Portland">005 Portland</option>
<option value="006 Anchorage">006 Anchorage</option>
<option value="018 PDC">018 PDC</option>
</select>
<input type="button" name="ViewReport" value="View" class="bnotes" onclick="GetInventory();">
</form>
<script language="JavaScript">
function GetInventory()
{
var InvForm = document.forms.InventoryList;
var SelBranchVal = "";
var x = 0;
for (x=0;x<=InvForm.SelBranch.length;x++)
{
if (InvForm.SelBranch[x].selected)
{
//alert(InvForm.SelBranch[x].value);
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
}
}
alert(SelBranchVal);
}
</script>
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Take a look at HTMLSelectElement.selectedOptions.
HTML
<select name="north-america" multiple>
<option valud="ca" selected>Canada</a>
<option value="mx" selected>Mexico</a>
<option value="us">USA</a>
</select>
JavaScript
var elem = document.querySelector("select");
console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
This would also work on non-multiple <select> elements
Warning: Support for this selectedOptions seems pretty unknown at this point
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal will be empty

Categories

Resources