select value of dropdownlist item jquery - javascript

HTML
<select id="selectDepartment">
<option value="1">120</option>
<option value="2">20</option>
<option value="3">140</option>
<option value="4">4120</option>
<option value="5">560</option>
<option value="6">451</option>
<option value="7">310</option>
<option value="8">656</option>
<option value="9">444</option>
<option value="10">555</option>
<option value="11">2560</option>
<option value="12">450</option>
</select>
jQuery
$("#selectDepartment").change( function() {
alert($("select option:selected").val());
});
the above function always shows value 1 on alert, when I select any one of the options

Your method of finding the selection option is vague. You're saying "Grab all <select>s". You then go on to grab the :selected option from each of them (of all <select>s on the page). Continued, .val() takes the first value off the top.
Simply put, you're always fetching the selected value of the first <select> found on the page. Assuming #selectDepartment isn't the first <select>, your value will never change.
Try to keep the scope to within the current <Select> using this:
$('#selectDepartment').change(function(){
var selopt = $('option:selected',this);
});
Note that I specify the scope to within the <select> that triggered the .change(). Also note this really isn't necessary as val() works just as easily:
var selopt = $(this).val();
Let jQuery do the heavy lifting. You really only need option:selected if you want control over styling that specific element, or you're working with a multi-select and want more control.

You can do something like this:
$("#selectDepartment").change( function() {
var selected = $(this).find(":selected");
});

Related

Static text in a select

I want my select to always show the same text, but "keep" the selected option value.
So e.g. my select always shows text "Language", but when I get the value of it in JS, it will return the value of selected option.
How do I achieve this? If there's no possibility for pure HTML + CSS, vanilla JS will do.
Edit: I want this because when i choose a value, I have a list of input boxes which get filled by this. They are then changeable; this select is only used to set the "base" of these inputs. I want this select to always show the same
text because I don't want to end up in a situation where select shows different text than actually the text in inputs that will be used.
Answer:
<select id="mySelect">
<option value="" hidden>Language</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
document.getElementById('mySelect').addEventListener('change', showSameValue)
function showSameValue() {
let select = document.getElementById('mySelect')
let firstOption = select.querySelector('option')
firstOption.value = select.value
select.selectedIndex = 0
}
Using the change event, you can capture the selected value then simply set the first option as selected and set its value to the selected value.
select = document.querySelector("select");
first = select.querySelector("option");
select.addEventListener("change",function(el){
first.value = el.target.value;
el.target.querySelector("option").setAttribute("selected",false)
el.target.selectedIndex = 0;
console.log(first.value);
});
<select>
<option value="">Language</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
This is a weird behavior but it can be done by
adding a hidden input element next to select
add the event listener to select (onchange) that would change the value of the hidden element and reset select to desired value 'Languages'
The key would be to have proper fields names, so when submitting the form select could be omitted and hidden would prevail.
You can store the selected value in a variable to meet your requirement and then use it wherever you need.
<select name="select" onchange="func(this.value);">
<option value="value1">Display always</option>
<option value="value2">Random Value</option>
</select>
And here's the Js function
var selected = "";
function func(selectedValue) {
document.getElementById( "select").selectedIndex = "0";
selected = selectedValue; // Use this after final selection
}
There are a few ways to achieve this, but using just a <select> would not be possible, I would not advise this on an accessibility UX principal.
One option would be to use a <span> or <div> that when clicked shows the options.

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>

Get Value of Select-Option In Loop with Jquery

I am trying to make an Asp.Net Mvc Ajax project.I have to take the value of select-option in a loop with jquery.All select's ids are same , names are same when I try it takes the first select's value.btw I have tried all things in this title: jQuery Get Selected Option From Dropdown. Can you help me please?
#foreach (var item in Model)
{
<select id="selSaat">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
}
Heres some JS code that will give you the selections value if there is only 1 select element on your page and the options within it contain values on them:
document.getElementsByTagName('select')[0].onchange = function(){
alert(this.value);
};
Heres a working demo for ya:
http://codepen.io/nicholasabrams/pen/OVOPYK
Targeting a <select> with native browser javascript with the onchange method will return the value selected when it occurs via user interaction.
http://www.w3schools.com/jsref/event_onchange.asp

detect change of selectmenu in jquery mobile 1.4

I am revisiting JQM after not using it for a few versions.
I have a simple selectbox
<select name="current-option" id="current-option" class="current-option" data-native-menu="false">
<option>Select Option</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
I want to be able to detect a change in this select box and then read it's value. It seems as though typical jquery methods don't work and I dont see an event for this in the api: http://api.jquerymobile.com/selectmenu/
Ok, you want to know value of option selected after change event occurs; You should do following:--
$('#current-option').change(function () {
var optionSelected = $(this).find('option:selected');
//var optTextSelected = optionSelected.text();
var optValueSelected = optionSelected.val();
});
I would request you to change name, id and class names for your select tag.
This isn't in a mobile environment, but it using the mobile plugins: Fiddle
HTML
<select name="current-option" id="current-option" class="current-option" data-native-menu="false">
<option>Select Option</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<label id='thelabel'></label>
JavaScript
$('#current-option').change(function () {
$('#thelabel').text($(this).val());
});
I took at look at the DOM after a select-menu is generated. It looks like the select-menu plugin will create a div with an id similar to the id of the select; in this case it would be current-option-listbox. The children of this div consist of several things, including the options. Based on this, I came up with the below solution:
var currentValue = ""; // keep track of the selected value
$('.ui-btn-inner', '#current-option-listbox').click(function () {
if ('a', this).text() !== currentValue) {
// the value changed - do stuff
currentValue = $(this).children('a').text();
}
});
This is heavily dependent on the plugin's render method remaining the same, or at the developer maintaining use of the plugin the code was designed around. I believe this will get you what you need.
Here is a Fiddle Demo
The event you need is 'selectmenuchange', jQuery mobile triggers this event for selects instead of 'change'.
It should go like this:
$('#current-option').on('selectmenuchange',function () {
$('#thelabel').text($(this).val());
});

multiple select element - onchange

I have a select element that allows for multiple selections. I'd like to display the selected values in another part of the page (in a div or something) as the user makes changes to what is selected.
Is the only way of doing this to iterate over the "options" and check if "selected" is true? this would not be preferable since each "onchange" event would require the entire select element to be iterated over.
Here's a fiddle that demonstrates how I am currently doing it, but I'm hoping maybe there's a better way than having to iterate over all the options on every "change": multiple select elment onchange fiddle
.val() on a multiple select returns an array.
See the snippet below as an example:
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
In your fiddle, I just used .val(). This returns an array
JSFiddle Link
$(function() {
$('#fruits').change(function() {
console.log($(this).val());
});
});
If you could use jQuery it might be as easy as:
$('select').change(function() {alert($(this).val())})
You could use blur instead of change, so that the select is only processed once, rather than on each selection. http://jsfiddle.net/2mSUS/3/
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
You can use the :selected Selector of jQuery instead, but I believe that under the hood, jQuery does a loop on the selected = true.
element.addEventListener('click', function(){alert(this.value)})
This is a solution in JS, you can port it over to jQuery pretty easily. The idea is to add a click listener to each option in the selection. This will not work in IE8 and below because of addEventListener, there are ways to get around this though.
I think this is a better approach then having to reiterate over the list. You will have to have a listener attached to each option though.
This works:
var MyControl = document.getElementById('Control_ID');
var newValue = MyControl[MyControl.selectedIndex].value;
Of course, Control_ID is the ID of the select control.
I'm doing a form submit. My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter by: text, value or selected
//stray is now ["Test", "Milk Free"] for example, depending on the selection
//...do stuff...
}
You could use a similar pattern for 'onchange'

Categories