I need to set a select to selected using data-val - javascript

I have a select I need to set to selected but the select is using a name and the options are using "data-val" and I can't change either:
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 2</option>
</select>
How can I set Option 2 to selected using JavaScript?

A couple ways that you could go about this;
You could be very explicit and set the value of the <select /> itself through;
document.querySelector('[name="properties[Liner]"]').value = "Option 2";
Or you could be a little bit more dynamic with the following;
document.querySelector('[name="properties[Liner]"]').value = document.querySelector('[data-val="2"]').value;
For the targeting of the name, you'll want to use [name="{some name}"]
For the targeting of a data-attribute, you'll want to use [data-val="{some value}"]
In this scenario, you could just specify "name" for querySelector and you'll get what you want because there's only one element with a name on the page (at least in your mini-scenario).

Code explanation in comments
(function(){
const selectEle = document.querySelector('[name="properties[Liner]"]'); // query the select the element
const setSelected = 2; // set the default value
const options = selectEle.querySelectorAll('option'); // query all the option element
options.forEach((option)=>{
const value = option.getAttribute('data-val'); // get the attribute data-val
if(value == setSelected){ // if matches
option.setAttribute('selected', true); // set selected
}
});
})();
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 3</option>
</select>

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>

I know part of the value of a select option, I would like set that option with JS?

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>

Javascript get value from select option based on label

Using either jQuery or pure JavaScript, how can I get the ID for a select option based on the label? So for example, given the following:
<select id="blah">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
If I have the label "Two" but I need to know the value associated with it, how can I get that value from this select? I don't want to simply select it, I need to know what the value is.
If the only reference you have is really the actual text content, then you'll have to loop through the elements and check the content of each one. Shown here with jQuery just because it's less to type:
var result;
$("option").each(function() {
if ($(this).text() == "Two") {
result = $(this).attr("value");
return false;
});
});
Another option:
$('#blah').find('option:contains("Two")').val();
(Pun intended?)
Get all the options and then use find to get the one with specific text.
const optionEls = Array.from(document.querySelectorAll("#blah option"));
const hasText = text => el => el.textContent === text;
const optionWithTwo = optionEls.find(hasText("Two"));
console.log(optionWithTwo.value);
<select id=blah>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>

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

Selecting option value of selected element with jquery

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>

Categories

Resources