Trying to get all options with a selected="selected" attribute on a page.
There are many of these instances on the page but I can only seem to save the first to an array.
How the selected="selected" shows up:
<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6" id="link_list_links__link_type" name="link_list[links][][link_type]">
<option value="frontpage">Store Frontpage</option>
<option selected="selected" value="collection">Collection</option>
<option value="product">Product</option>
<option value="catalog">All Products</option>
<option value="page">Page</option>
<option value="blog">Blog</option>
<option value="search">Search page</option>
<option value="http">Web Address</option>
</select>
What I have tried :
$('#link_list_links__link_type option:selected').map(function () {
return $(this).val();
});
It only returns the first selected="selected" option and not the rest of the iterations.
How do I return all of the options on the page with selected="selected"?
What am I doing wrong?
The problem is the id you have used, ID of an element must be unique, so when you use id-selector it will return only the first element with the said id. which means #link_list_links__link_type selects only 1 select element thus you are getting only one value.
A unique identifier for the element. There must not be multiple
elements in a document that have the same id value.
One solution here is to use a class to group similar elements so
<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6" name="link_list[links][][link_type]" class="link_list_links__link_type">
then
var array = $('.link_list_links__link_type option:selected').map(function () {
return $(this).val();
}).get();
Related
I want to get an array of values which is selected by <select> tag with multiple attributes by using querySelector, NOT jQuery.
I googled on that, but Google lists only about selecting multiple elements by using querySelector. In my case, I want one select element with multiple attributes.
I gave up searching on that, I just tried to code with this <select> tag.
<select id="bgmSources" className="bgmSelector" multiple="multiple">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
In JavaScript, I tried as below, but nothing worked.
const values = document.querySelector("#bgmSources").value;
console.log(values);
const selectedOptions = document.querySelectorAll("#bgmSources option:selected");
selectedOptions.forEach(option => console.log(option));
Is there a way to get the array of selected options in <select> tag with multiple attributes?
You can select the children options which are :checked, and then get each of those selected options' values:
bgmSources.onchange = () => {
const selectedOptionVals = Array.from(
bgmSources.querySelectorAll(':scope > option:checked'),
({ value }) => value
);
console.log(selectedOptionVals);
};
<select id="bgmSources" className="bgmSelector" multiple="multiple">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
You can't use .value to get a meaningful result for multiple, unfortunately, and you have to use :checked, not :selected.
I want to achieve:
If I select "16" in first select box and bigger value in second, for example "17", then in second select automatically changing to "16".
Just if value in first select box is lower than second, always change to same values, for example 16 to 16, 18 to 18.
<select id="from_age_js" name="from_age" class="select-advertise-style">
<option value="f13">13</option>
<option value="f14">14</option>
<option value="f15">15</option>
<option value="f16">16</option>
<option value="f17">17</option>
<option value="f18" selected>18</option>
<option value="f19">19</option>
<option value="f20">20</option>
</select>
—
<select id="to_age_js" name="to_age" class="select-advertise-style">
<option value="t13">13</option>
<option value="t14">14</option>
<option value="t15">15</option>
<option value="t16">16</option>
<option value="t17">17</option>
<option value="t18">18</option>
<option value="t20" selected>20+</option>
</select>
That's an easy one, in your case, with pure javascript, I would do something like this:
function checkit()
{
//Store the two dropdowns for easy reference
var fromAge = document.getElementById('from_age_js');
var toAge = document.getElementById('to_age_js');
//Verify if the toAge value is minor, to see if the conditional code will be executed
if( fromAge.options[fromAge.selectedIndex].value >
toAge.options[toAge.selectedIndex].value)
{
//In that case, match the values to be the same...
document.getElementById('to_age_js').value =
fromAge.options[fromAge.selectedIndex].value;
}
}
And you just have to add that function to where you want it to be called. I would choose to add the onchange event from Javascript within the select dropdowns. Like this:
<select id="from_age_js" name="from_age" class="select-advertise-style" onchange="checkit();">
You can see a working example here:
https://jsfiddle.net/8cmad3tz/19/
i am trying to get the query parameter for http://url.com?send_volume=send_300_gb and then set a form select option based on this.
I can grab the get value and assign to var to use in the assignment but for the life of me can't understand why i can't get the option to set as selected:
<script type="text/javascript">
//This will return a given query string parameter from the current url
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var send_volume_value = getParameterByName('send_volume');
$(document).ready(function () {
$("select[name='send_volume'] > option[value="+ send_volume_value +"]").attr('selected','selected');
});
</script>
Select Form looks like this:
<select class="hs-input" id="send_volume-33ab6f27-e084-4f5d-9690-76e8fec2316d_8893" name="send_volume">
<option value="__PLACEHOLDER__">- Please Select -</option>
<option value="send_300_gb">Send up to 300GB/month</option>
<option value="send_500_gb">Send up to 500GB/month</option>
<option value="send_1_tb">Send up to 1TB/month</option>
<option value="send_custom">Custom</option>
</select>
If the value of the parameter send_volume matches one of the values of the options for example lets say
send_volume == "testval"
and the options are
<select name="send_volume">
<option value="">Select one</option>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
<option value="val4">Val 4</option>
</select>
Then this is how you should "select" an option
$("select[name='send_volume']").val(send_volume);
<select> elements do not honor the value attribute, however their DOM API does support a value property shich can be used to set the select's value.
$("select[name=send_volume]").val(send_volume_value);
However, the way you are doing it should also work, but I suspect that either the value of send_volume_value is incorrect, or there is no option with that value. Basically, there are no elements matching your selector in the document.
Is it possible to detect if no option was explicitly selected in a select box?
I have tried these methods but none of them works:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
Trial 1:
alert($('#select option:selected').length); // returns 1
Trial 2:
alert($('#select option[selected=selected]').length); // returns 1
Trial 3:
alert($('#select option:selected').attr('selected')); // returns 'selected'
Any ideas SO people?
Try This:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>
Use this JS:
$('#btncheck').click(function(){
if ($("#mySelect ")[0].selectedIndex <= 0) {
alert("Not selected");
}
else
alert("Selected");
});
It will check if your dropdown was selected.
Try this fiddle: http://jsfiddle.net/aPYyt/
Hope it helps!
PS: You will have to make first value as default value.
This is how a normal select element works: the first option is selected if no other option has selected attribute set. The simplest workaround is to add an empty option as the first option, like this:
$(function() {
console.log($("#mySelect").val());
console.log($("#mySelect").get(0).selectedIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">-- select an item --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
then test one of these conditions:
$("#mySelect").val() === "";
$("#mySelect").get(0).selectedIndex === 0;
$("#mySelect option:selected").index() === 0;
A select box always has a value. If you don't manually change from the default value, you still have a value. For checking for explicit changes, as you say, you could monitor change:
$('#select').change(function() { $(this).data('changed', true); });
Your condition, then, would be:
if(!!$('#select').data('changed')) { ... }
The more common way of achieving something similar would be to insert a placeholder value at the top:
<option value="0">Please select one item</option>
... and test for
$('#select').val() == '0'
If you need to find out whether the select has been changed from its original value, i.e. the above test, but making sure that the user doesn't switch back to the default, you coul simply store the original value at page load:
$('#select').data('original-value', $('#select').val());
And check for
$('#select').val() != $('#select').data('original-value');
By default whatever option comes on index 0 is considered by browser as selected. The solution to problem would be inserting a dummy option at index 0 and before form submission you can validate it using something like
if($("#selectBox option").index("option:selected")>0)
$("#myForm").submit();
var $inputs_select_options = $('option:selected');
// remove empty(first option as default , value=="" ) options:
$inputs_select_options = $inputs_select_options.filter(function() {
return this.value.length; //check by length value
});
I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});