Get value of selected option from drop down using jquery. - javascript

I have a problem when I get the values ​​of Selected options.
Let me explain I have a list of options :
<select>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
<option value='4'>Option4</option>
<option value='5'>Option5</option>
</select>
I get the values ​and I inserts them into a variable for each Selected option and I put them in an array like this :
$("select option:selected").each(function()
{
var listValO = new Array();
var idOption = $("select option:selected").val();
listValO.push(idOption);
});
If I choose only one selected option, it works but when I select several options at the same time, the each () function inserts in the array the same value for the number of selected options.
when I click on the submit button, the array contains listValO several times the same value.
<select>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
listValO returns just 3 times [1,1,1]. In fact, it seleted the first which I clicked or I want in my array [1,2,3].
Sorry for English mistakes if any. I hope you understand my problem and thank you for your future response.

As well as the other answers (using multiple attribute, and using $(this)), you are re-declaring the array for each occurrence of a selected option. Try declaring it outside:
var listValO = new Array();
$("select option:selected").each(function()
{
var idOption = $(this).val();
listValO.push(idOption);
});

Firstly, you need to add the multiple attribute to the select so you can select multiple options. Second, you're redeclaring a new array inside the each callback, so at the end you'll only ever have one option.
You should use .val() instead:
Markup:
<select multiple>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Javascript:
var optionsArray = $("select").val();

You need to add attribute multiple in select to select multiple value:
<select multiple="multiple">
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Js code: You are iterating over the selected options, you should rather iterate over to select itself to ensure that selected options are added to array once only.
var listValO = new Array();
$("select").each(function()
{
listValO.push($(this).val());
});
//console.log(listValO) for test purpose
Working Demo

Related

how to get last selected option in multiple select in javascript [duplicate]

This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 11 days ago.
I want to get the last selected <option> in a <select multiple> in javascript not jquery!
The last selected option means the last option selected by the user.
Not that the last option element in the select element!
I try:
<select multiple="multiple" onchange="changeEvent(this)">
function changeEvent(selectTag) {
console.log(selectTag.value);
}
I expected to get the last <option> selected
The value property of the select tag only returns the value of the selected option if the multiple attribute is not set. If the multiple attribute is set, you can use the options property of the <select> element to get an array of all the options and check which ones are selected.
Here's an updated version of the function with JavaScript:
function changeEvent(selectTag) {
let selectedOptions = [];
for (let i = 0; i < selectTag.options.length; i++) {
if (selectTag.options[i].selected) {
selectedOptions.push(selectTag.options[i].value);
}
}
console.log(selectedOptions);
}
<select multiple="multiple" onchange="changeEvent(this)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
</select>
To get all the selected options, use selectedOptions on the selectTag.
For the 'last' option, use the default selectTag.value.
Remember that .value will only contain the last selected value, so if you'd un-select some value, the previous selected will be set as value of selectTag.value
function changeEvent(selectTag) {
const allSelectedValues = Array.from(selectTag.selectedOptions).map(t => t.value).join(', ');
console.log(`All selected: ${allSelectedValues}`);
console.log(`Previous: ${selectTag.value}`);
}
<select multiple="multiple" onchange="changeEvent(this)">
<option>foo</option>
<option>bar</option>
<option>foobar</option>
</select>

How to get all the selected option from multipal selectbox value using jQuery

I have a long dynamic form which has several Select Option like
<select class="common_dt_select" id="select_15" data-col-index="15">
<option value="">All CC Status</option>
<option value="0">Dead</option>
<option value="1">Active</option>
<option value="2">Frozen</option>
</select>
<select class="common_dt_select" id="select_23" data-col-index="23">
<option value="">All</option>
<option value="0">No</option>
<option value="1">Yes</option>
</select>
I want to get all the selected option value and data-col-index value using jQuery.
I know I have to loop it by a common class so I have given common_dt_select but I cannot able to get the data.
How i want is
some loop that will run
if (sel_val != '') //I only want that value which is not blank
console.log(sel_val);
console.log(data_tag_id);
end of if
end of loop
Codepen
$('.common_dt_select').each(function() {
var value = $(this).val();
var colindex = $(this).data('col-index');
if(value.length) {
console.log(colindex);
console.log(value);
}
});
You can simply use below code
$('.common_dt_select :selected').each(function(i, sel){
alert( $(sel).val());
});

sort a dropdown list with added atrribute or id

Currently I am working on a site where I do not have access to the perl generated options of a drop down list. The drop downs are populated dynamically and not all options are available to all users.
The code I am able to work with is shown here.
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;" ></select>
PRIMARY_POS
populates each option that is able to be selected.
The actual output as seen when the page renders is
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;">
<option value="0">None Selected
<option value="155935">Option4
<option value="155934">Option3
<option value="155905">Option2
<option value="155933">Option1
<option value="155932">Option5
</select>
What I need to be able to do is set a sort order based on a hidden attribute that is assigned based on the text value
So in the above example. I need the drop downs ( Important as their are mulitple drop downs on the page ) to be able to be sorted by a not yet created attribute
So that the above code might then be
<option value="0">None Selected
<option sortvalue="5" value="155935">Option4
<option sortvalue="4" value="155934">Option3
<option sortvalue="3" value="155905">Option2
<option sortvalue="2" value="155933">Option1
<option sortvalue="1" value="155932">Option5
</select>
The sortvalue being set base don the Text value of the option select. So that a sortvalue of 5 would be assign to Option4. Just a smaple as the text will need to be assigned.
End result should be that the Drop down list now has a custom attribute of Sortvalue and the select drop down is now sorted by that value.
Once again, I can not directly change the attributes but can manipulate the results. Hope that was easy to follow, which I doubt :/
You can create an object where the keys are the text and values are sort order. Then loop over options and add attribute based on that map
var optsMap = {
"Option4": 5,
"Option5": 1
......
};
var $select = $('select[name=PRIMARY_POS]')
$select.find('option').attr('data-sortvalue', function(){
return optsMap[$(this).text()] ||0;
}).sort(function(a,b){
return +($(a).data('sortvalue')||0) - +($(b).data('sortvalue')||0);
}).appendTo($select);
You can then read the value using:
$select.change(function(){
alert($(this).find(':selected').data('sortvalue'));
})
If all you are needing is sorting and don't need attribute can remove one step
DEMO
Common practice is to prefix those "added attributes" with data. You could try something like this with jQuery, if I'm understanding you correctly.
Example fiddle: https://jsfiddle.net/30cvudz8/7/
<select class="my-select">
<option data-sort-value="3" value="1">Option 1</option>
<option data-sort-value="5" value="2">Option 2</option>
<option data-sort-value="4" value="3">Option 3</option>
<option data-sort-value="1" value="4">Option 4</option>
<option data-sort-value="2" value="5">Option 5</option>
</select>
var optionList = new Array();
$('select.my-select option').each(function() {
optionList[optionList.length] = $(this).attr('data-sort-value')+'::'+$(this).val();
});
optionList.sort(); // sort it
var newOptionList = '';
for(var i = 0; i < optionList.length; i++) {
// recreate option
var parts = optionList[i].split('::');
newOptionList += '<option value="'+parts[1]+'" data-sort-value="'+parts[0]+'">Option '+parts[1]+'</option>';
}
// wipe and repopulate the select list
$('select.my-select').html(newOptionList);
To add an attribute (like data-sort-value) after you have a select list, you can do something like this:
$('select.original option').each(function() {
var sortingValue = getSortingValueFromText($(this).text());
$(this).attr('data-sort-value', sortingValue);
});

Javascript dropdown updates the price based on the users selection version 2?

I needed some help updating the price on a page based on a dropdown selection.
This is what code with some help we came up with:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Which works if my dropdown is structured like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
But if for any reason the the dropdown was to be like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="3">Metal</option>
<option value="4">Cloth</option>
<option value="5">UPVC</option>
</select>
it would not work (because the value option is not 1,2,3). The value is the id for the material. Hope this makes sense and that someone can help me to get this working.
Thanks
Dino
You're changing the price based on the value, and using that as the item from your price array... but your price array only has 4 values. In your second select, you're asking it to return price[4] or price[5], which would cause an error.
Change this:
var price = new Array('','$2.00','$45.00','$60.00');
To this:
var price = new Array('','$2.00','$45.00','$60.00','$cloth price','$upvc price');
Fiddle here.
EDIT: Updated method (with minimal change to your existing layout/logic)
$(function() {
$('select[name=material]').change(function() {
var price = $(this).val().split("_");
$("#id").html(price[0]);
$("#price").html("$" + price[1]);
});
});
HTML (adding the price to each option value, split by "_" in JS)
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="1_2">Wood</option>
<option value="2_2">Plastic</option>
<option value="3_45">Metal</option>
</select>
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="3_60">Metal</option>
<option value="4_50">Cloth</option>
<option value="5_80">UPVC</option>
</select>
<div>ID: <span id="id">TBD</span><br />Price: <span id="price">TBD</span></div>
Just select price using the selectedIndex of your <select>:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[this.selectedIndex];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Or, use an object instead of an array for price:
var price = {
"4": "$2.00",
"5": "$45.00",
"6": "$60.00"
};
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Update: Here is a jsfiddle with updated code to get your single price array to work:
Your price arrayhas a length of 4 and starts at index 0.
Your first option must have a value of '0' or it will return undefined from the price array:
<select name="material">
<option value="0">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
When you set your option values from 3 to 5, you are trying to access non-existent indexes outside the bounds of your price array.

Javascript: Get array value when I select the option in the drop down list

I hope that someone would be able to help me to solve this simple problem.
My goal is to get the value in the array from selection drop down list.
Basically, I create an Array in Javascript and a selection drop down list in the body.
<script type="text/javascript">
var even = new Array(2, 4, 6);
</script>
.
.
.
<select id="evenNumbers">
<option value="1">two</option>
<option value="2">four</option>
<option value="3">six</option>
</select>
My question is how can I get the value in the Array if I select the option from the drop down list? e.g. when I select "two" from the drop down list, but I can get the value of "2" in the array in order to do some calculation.
your select box will look like this
<select >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
if you want to populate values putting a for loop.
for getting selected option value
this.options[this.selectedIndex].value
http://awesomerails.wordpress.com/2007/12/04/get-the-value-of-a-selected-option-with-javascript/
document.getElementById('evenNumbers').onchange = function() {
var index = this.value - 1; // array indices start at 0
alert(even[index]);
}

Categories

Resources