jQuery - Get all items in a multiple select list - javascript

I'm a jQuery noob and I haven't been able to find what I want in the documentation, perhaps because I do not know what to search for. I need to get ALL values of a dropdown list.
I am currently doing:
<select id="cars" multiple="multiple" class="form-control">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
And to access that, my Javascript is:
"cars" : $('#cars').val()
Unfortunately, this only returns a list of SELECTED items. Is there a simple way to return the entire list?
Thanks,
Tim

If you want to do something like get all the values and put them in an array, you could do:
$("#cars option").map(function(){ return this.value }).get()

$('#cars option') would return all the <option> elements.

selector
$('#cars option')
will give you list of options.

You can get the children of the div id cars by using .children(), or simply $(#cars option):
var ary = [];
$('#cars').children().each(function () {
ary.push($(this).val()); //put them in array
});
And you can access the children with $(this).val(), and store them in an array

Related

WebdriverIO - Collect drop down elements into an array

I have a drop down in my application that looks similar to this -
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
How would I collect the car brand options into an array? I know the java selenium bindings have the select class to help with this however there doesn't appear to be an equivalent solution using webdriverio?
You should be able to use .elements method based on tag for the option tag this should return you JSON Objects.
Here is the link that states that:
http://webdriver.io/guide/usage/selectors.html
You need to find all the <option> elements in the select list, and then convert the list of elements to a flat list of values using the .map() method:
browser.getElements('option').map(option => option.getText());

Change a Select Option value with no id/class

There's this website that I want to change how they display their dropdown menu.
http://i.stack.imgur.com/Wu718.jpg
I wanted to make it so that the default value is "Items for Sale", instead of "Forum Topics"
Here's their source code.
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
Since I don't really care about how it looks, I just want to change the value="topics" to value="s" even without changing the texts.
I've read some tutorials, but they mostly use IDs and Classes as a selector, in this case, how do I target this Select from many other in their website and change the value.
You can use:
$('select[name=sec]').val('s');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
I think this is what you're describing in the comments below:
var dropdown = $('select[name=sec]');
// change the s option to items
dropdown.find('option[value=s]').attr('value', 'items');
// change the topics option to s
dropdown.find('option[value=topics]').attr('value', 's');
// change the dropdown's value to s
// (first option should continue to be selected because its value is now s)
dropdown.val('s');
// (this is for demo purposes only)
dropdown.after($("<div>").text("New HTML is: " + dropdown[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You can use the name or any other attribute.
for css
select[name="sec"]
or jquery
$('select[name="sec"]').
DEMO inspect element from your browser to see the changes
you can select a select dropdown list with select[name=sec] and select the first option with option:first
$('select[name=sec] option:first').val('s');
and if you need to change any of options just use .eq()
$('select[name=sec] option').eq(0).val('s'); // eq(0) for the first option element . eq(1) for the second option element ...
If you want to make selected an other option use this code:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
This script removes the default selection (the first option) and select the option which has "s" value. For the Demo:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You have to find this element in the DOM. For this you should find the first parent container element of the which has ID or CLASS attribute. From that element you can create a search for the element what you want by using the .find() method.
If there're more element which has name attribute with "sec" value you should build a chain of find which separate that you want. For that you can use these function templates:
$(#CONTAINER_ID).find(.SUBCONTAINER_CLASS).find(ELEMENT_TYPE);
$(#CONTAINER_ID).find(SUBCONTAINER_TYPE).find(OTHER_SUBCONTAINER_TYPE:eq(X));

Handlerbars template for handling forms

Currently I create a Handlebars template for each form and use value={{user}} in them. So I can fill any form easily for updating any entity. But select, radio and ckeckboxs are different. Is there any clean way to populate these elements too. They do not have value attributes.
<select id='select'>
<option selected value=user name=test>test</option>
</select>
as you can see, you can control the value of select by set "selected" attribute to specific options.
Or you can try embed some javascript code like
document.getElementById('select').value={{user}}
You need to make sure you have options with correct value attributes set
You can achieve this by making use of the each helper.
<select>
{{#each options}}
<option>{{this}}</option>
{{/each}}
</select>
Where options is a plain array (["apple", "banana", "pear"]).
You can find more info on the homepage. There's also an example where your array contains object, which could be useful should you need to specify value attributes.
On stackoverflow, I found this reply :
How to set selected select option in Handlebars template
With a very good solution (from #janjarfalk edited by #BlaM) :
With this partial (using Jquery) ...
window.Handlebars.registerHelper('select', function( value, options ){
var $el = $('<select />').html( options.fn(this) );
$el.find('[value="' + value + '"]').attr({'selected':'selected'});
return $el.html();
});
You can wrap selects in your Handlebars template with {{#select status}}...
<select>
{{#select status}}
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
{{/select}}
</select>

using jquery to select an option in a select based on a user-defined variable

Given a user-defined variable jstatus, I want that that particular variable should be selected in a given list of options.
My list is like this:
<select name='job_status' id='job_status'>
<option>Pre-press</option>
<option>Printers</option>
<option>Cutting</option>
<option>Final touches</option>
<option>Delivery</option>
<option>Ready</option>
</select>
And somewhere in my javascript code after setting the value of jstatus, this is my jquery:
$("#job_status option[value='"+jstatus+"']").attr('selected','selected');
But it's not working. What's the right way to do it?
Easiest way is to set the value directly:
jQuery("#job_status").val(jstatus);
You need to add value to selector first.
<option value="Pre-press">Pre-press</option>
The problem is that your select list has no "value"-property on its options
<select name='job_status' id='job_status'>
<option value="val1">Pre-press</option>
<option value="val2">Printers</option>
<option value="val3">Cutting</option>
<option value="val4">Final touches</option>
<option value="val5">Delivery</option>
<option value="val6">Ready</option>
</select>
<script>
$( 'select option[value="val3"]' ).attr( 'selected', 'selected' );
</script>
You can also use jQuery's val() method
$( 'select' ).val( 'val3' )
this would have the same effect as the above
If you still prefer using a direct selector, there's :contains for you to select element by its contents. For your case it goes pretty much like this:
$("#job_status option:contains("+jstatus+")").attr('selected','selected');

How do I select an option by class?

I tried using $('.className').show(); and $('.className').hide(); but it doesn't seem to work in IE. Is there another way to group options by class in a drop down list? I found this question but the answer is looking for the value "a" or "c".
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
How do I look for the actual class?
EDIT
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
I've never seen anyone try to call hide/show on option elements before, and I imagine IE just doesn't allow you to do that. The selection is probably matching just fine, but IE is not hiding the elements. The selection for removing would be the same as for calling show hide...
$('.className').remove();
or
$('option.className').remove();
or
$('#theSelect option.className').remove();
You can add the disabled attribute to the options you don't want to use:
http://jsfiddle.net/sadmicrowave/Fnvqb/
$('select[class~="cactus"]')
$('option[class~="cactus"]')
javascript:(function(){
var out = "hi\n";
out += $('*[class~="cactus"]').html2string() ;
alert( out );
})()
For future reference, instead of describing in words the html ... show actual html
This demonstration code shows one way of how you can achieve option filtering... it would need modification to determine which candidate items are removed as I just hardcoded for purpose of demonstration, but it shows you what you need to consider - when you remove the items, you need to consider the ordering by which they're added back. The easiest way to bypass this problem is to keep a copy of the original list and then when you unfilter, just remove the remaining items, replacing them with what was originally there - otherwise you have to worry about keeping sort data.
So here's my drop down definition:
<select id="mySelector">
<option class="group1">Item 1</option>
<option class="group2">Item 2</option>
<option class="group1">Item 3</option>
<option class="group2">Item 4</option>
<option class="group1">Item 5</option>
</select>
<input type="button" id="removeItems" value="Remove candidate items" />
<input type="button" id="addItems" value="Add them back" />
And the jquery to filter/restore the items:
$(function () {
var originalOptionData;
$("#removeItems").bind('click', function () {
/* store original copy for rollback */
originalOptionData = $("#mySelector option");
$("#mySelector option.group2").remove();
});
$("#addItems").bind('click', function () {
var selector = $("#mySelector");
selector.children().remove();
selector.append(originalOptionData);
});
});
This could be turned into a select filter jquery plugin relatively simply I suppose, but I didn't go that far...

Categories