I'm trying to use jquery to select the option value of the selected element in an html dropdown.
HTML
<select class="select1">
<option value ="0">" + state.greens[0].name + "</option>
<option value ="1">" + state.greens[1].name + "</option>
<option value ="2">" + state.greens[2].name + "</option>
</select>
The option values represent an index position in an array that I can load to generate additional data about objects within them.
I'm trying to use jquery to grab the option value of whatever dropdown element is currently selected.
Right now I'm using this code but it's not working:
JQUERY
var a = $(".select1 option:selected");
However it's not bringing back "1", "2", "3", etc.
When I run console.log(a) I get the following:
Not sure what's happening.
The idea is that I can use the variable a to load data like state.greens[a].price, state.greens[a].ingredients, etc.
You are almost there. Just give:
var a = $(".select1 option:selected").attr("value");
Or give this:
var a = $(".select1").val();
You need to get the value of the <select>.
var a = $(".select1").val(); // is the simple solution
Try this..
HTML
<select class="select1" id="select1">
<option value ="0">Option 1</option>
<option value ="1">Option 2</option>
<option value ="2">Option 3</option>
</select>
Pure Javascript solution
document.getElementById("select1").addEventListener("change", function(){
var a = document.getElementById("select1").value;
alert(a);
});
Check out this Fiddle
Snippet
document.getElementById("select1").addEventListener("change", function(){
var a = document.getElementById("select1").value;
alert(a);
});
<select class="select1" id="select1">
<option value ="0">Option 1</option>
<option value ="1">Option 2</option>
<option valuae ="2">Option 3</option>
</select>
Related
I would like to set an option in a select element based on the substring which will be contained in one of the option values. I have a solution but it seems quite convoluted to me.
I get the values of the options and put them in an array, loop through the values and check if the value includes a string I am looking for when it does I set that value as the select value. There must be an easier way!
I get the values of the options in the following way.
// Get the select element where you can select a procinve with a pull-down
var provincePullDown = document.querySelector(".select-provincie");
// Array containing the values of the select options
var optArray = Array.from(provincePullDown.options);
var optArrayValues = [];
optArray.forEach(el => optArrayValues.push(el.value));
I then loop over the values looking with a likely substring.
// Loop over the values in the select options
optArrayValues.forEach(function (el) {
// Look for the option containing the right province
if (el.includes(selectedProvince)) {
// Set the selected option from the select element
provincePullDown.value = el;
}
});
The option values look something like this sting (3) and the substring like this string.
I would like to know if there is an easier way as to me this seems an overly convoluted solution. And keeping maintenance in mind I would like an clear solution that I will still easily understand in 6 months.
The page is created by Drupal so I also control what html is outputted and the option values are inserted in the Drupal template.
Let me also state that I am not a fan of jQuery even though the project does load jQuery by default.
As querySelector() support any valid CSS selector, you can try with contains (*=) Attribute selector:
[attr*=value]
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
var selectedProvince = 'province';
document.querySelector(".select-provincie option[value*='"+selectedProvince+"']").selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can also use Template Literals for cleaner syntax:
var selectedProvince = 'province';
document.querySelector(`.select-provincie option[value*='${selectedProvince}']`).selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can directly point to the option value if the regext is just a simple contain
const optToSelect = document.querySelector('option[value*=${SUBSTRING}]');
document.querySelector("select").selectedIndex = optToSelect.index;
You can use plain DOM methods with find and includes:
function updateOther(source) {
let value = source.value;
let sel = document.querySelector('.select-provincie');
sel.selectedIndex = [].find.call(sel.options, opt => opt.value.includes(value)).index;
}
<select onchange='updateOther(this)'>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select class="select-provincie">
<option value="province1" selected>Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
But it's not fault tolerant: if a suitable value isn't found, it will throw an error (as do other answers). :-)
JQuery is interesting precisely when you want simplify solutions and ensure it is practical in terms of optimization. So I want to bring you a JQuery solution.
var selectedProvince = 'province3';
$(".select-provincie > option").each((index, elem) => {
if (elem.value == selectedProvince) {$(elem).attr('selected', true)};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select_provincie">
<select class="select-provincie">
<option value="province1">Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
</div>
Lets say I have a select with some options inside it.
<select>
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
Is there a way to grab whatever is between the option tag if our value is something different? For instance how to grab 'dog'. 'cat', or 'bird'
EDIT: MORE DESCRIPTION
Select the elements, then do whatever you want with it
document.querySelectorAll('select option').forEach(e =>
console.log(`found option with value: ${e.value} and innerText: ${e.innerText}`)
)
<select>
<option value=1>dog</option>
<option value=2>cat</option>
<option value=3>bird</option>
</select>
You can get the text inside the option tag using jQuery in this way: $("select option").text() - this will return a list ['dog', 'cat', 'bird']
p.s if you want to filter with a specific value, then use: $("select option[value='1']").text()
You could get text from all <option> tags by taking document.getElementsByTagName for the wanted tags.
Array.prototype.forEach.call(
document.getElementsByTagName('option'),
e => console.log(e.text)
);
<select>
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
Answered using jquery because i love it
$(document).ready(function(){
$('#dropdown').on('change',function(){
alert($(this).val() + $(this).find(':selected').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
using javascript , getting selected option's text :
<select onchange="getTextVal(this)">
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
And javascript :
function getTextVal(e){
console.log(e.options[e.selectedIndex].text);
}
JsFiddle :
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());
});
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);
});
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.