How to get attribute from selected option of select in jQuery? - javascript

I have the next selectbox in HTML:
<select id="listbox-taskStatus" class="selectpicker">
<option status="0">In progress</option>
<option status="1">Not started</option>
<option status="2">Done</option>
<option status="3">Failed</option>
</select>
I want to read the attribute value from selected option.
If just to take the value, it's simple:
var value = $('#listbox-taskStatus').val();
But what should I do, if I want to get the attribute value from selected option?
I know, that .attr() must help, but when I tried to use it I've got the incorrect result.
I've tried the next:
var status = $('#listbox-taskStatus option').attr('status');
But the returned value is always 0 despite on fact I was selecting different option.
What's wrong, how to solve my problem?

Use :selected Selector
var status = $('#listbox-taskStatus option:selected').attr('status');
However, I would recommend you to use data- prefixed attribute. Then you can use .data()
var status = $('#listbox-taskStatus option:selected').data('status');
DEMO

var optionAttr1 = $('#listbox-taskStatus').find('option:selected').attr("status");
var optionAttr = $('#listbox-taskStatus option:selected').attr("status");

Related

find a select option with same value as select data-status and load option as "selected" with jquery

I am loading 2 separate ajax responses into a select dropdown and the select dropdown will have a data-status, what I am looking to achieve is to loop through the options and find the option that has the same value as the select data-status and load it as "selected".
Given my html code generated from my ajax call:
<select class="orderCurrentStatus" data-status="1215458">
<option value="608653">Goods Received</option>
<option value="608654">Purchase - Awaiting Payment</option>
<option value="608655">Purchase - Payment Received</option>
<option value="766705">EXCHANGE FEE PAID</option>
<option value="838627">Order Refunded</option>
<option value="1215458">Goods Dispatched</option>
<option value="2322397">Paid - Custom Order Under Production</option>
<option value="2384172">WRONG/INCOMPLETE ADDRESS!</option>
<option value="2544576">Paid - Awaiting Pre-Ordered Items</option>
</select>
My attempt to make it work:
var order_status = $(".orderCurrentStatus").data("status");
var options = $(".orderCurrentStatus option");
if (options.val(order_status)) {
$(this).attr("selected");
}
I just can't get it to work.
You can just use the attribute selector [value="'+ order_status +'"] in order to select an option element that has a value equal to the variable order_status.
From there, set the selected property value to true or selected.
$('.orderCurrentStatus option[value="'+ order_status +'"]').prop('selected', true);
There were a couple issues with your initial code.
The variable this refers to the global object, in this case the window object, since there is no functional scope.
If you don't specify a value when using the .attr() method, the selected attribute value is returned. You need to specify a second parameter in order to set a value for the selected attribute. Specifying true or selected will work in your case. However, the .prop() method is better suited for this since you should be setting the property.
Additionally, if you want to do this for all select elements, then you could iterate over them, then retreive the data-status attribute value, and set the corresponding option element's selected property:
$('select').each(function () {
var status = $(this).data("status");
$(this).find('option[value="'+ status +'"]').prop('selected', true);
});
You should somehow check if an option with the value specified exists! This what you actually tried is assigning a value to every option element.
This should be simple solution:
var order_status = $(".orderCurrentStatus").data("status");
if( $('.orderCurrentStatus option[value=' + order_status + ']').length )
$('.orderCurrentStatus option[value=' + order_status + ']').attr('selected','selected');
You could verify the code on JSFiddle:
https://jsfiddle.net/cwma9h5m/
You can always iterate through the option values to match with the data-status value.
var status = $('.orderCurrentStatus').data("status");
$('.orderCurrentStatus option').each(function(){
if( $(this).val()==status){
$(this).prop('selected', true);
}
});

How to get the Index of an option based on a value

So I currently have a select field that looks something like this:
<select id = "foo">
<option value = "example">This example</option>
<option value = "example2">This example Again</option>
<option value = "bar">This is just a bar</option>
</select>
and if the submitted form returns back with an error, it sends me back all the values in a object, and I need to repopulate the form.
My question: how can I efficiently get the index of value bar, without having to use jQuery?
Is there a way to do it without having to loop through each of the options, checking the value against the one I have, then setting it as checked if it is the same as my value?
Any insight is greatly appreciated
You can combine querySelector() with index:
var selected = document.querySelector( '#foo > option[value="bar"]' );
console.log(selected.index);
jsFiddle Demo

Get Value of Disabled Option in Select Multiple Jquery

I have a multiple select on my page, and I have an option disabled so that the user can't unselect them, but I can't work out how to get the value of the disabled option.
My code so far
// Get selected positions
var $selPositions = $('select#empPositions').val();
HTML
<select name="empPositions[]" id="empPositions" style="width: 370px;" multiple="" data-placeholder="Choose a Position" required="">
<option></option>
<optgroup label="Admin">
<option disabled="">There are no positions assigned to Admin</option>
</optgroup>
<optgroup label="Information Technology">
<option value="1" selected="" disabled="">IT Developer</option>
<option value="2">IT Geeks</option>
</optgroup>
Note the disabled option changes based on other variables, but it only gives me selected non-disabled values. Can anyone let me know if this can be done and how?
I'm using Chosen, hence why the disabled option
Fiddle: http://jsfiddle.net/c5kn5w75/
I did find this article on the JQuery Bug Site which said
The long-standing logic in .val() ensures that we don't return disabled options in a select-multiple. The change just applies the same behavior for select-one now for consistency. You can get to the disabled option value through $("select").prop("selectedIndex") if you need it.
But that didn't work for me.
DEMO
var opt = $('#empPositions option:selected').map(function(i,v) {
return this.value;
}).get(); // result is array
alert( opt );
Please bear in mind that when you submit the form disabled options wont be submitted even if they are selected. If you're submitting via AJAX, then you can grab the values as shown above.
Also bear in mind that $('option[disabled]').val() will return the value of the first disabled option element and $('option[disabled]:selected').val() the value of the first selected disabled option.
If there's always just one selected disabled option element you can target it using:
var opt = $('#empPositions option[disabled]:selected').val(); // result is string
You can get the value of a disabled element by doing something like this:
$('option[disabled]').val();
//==================================
// Option-1:
//==================================
// Get Disabled Options
var disabled_options = $('#selectboxID option[disabled]');
// Get Disabled Ids
var disabled_options_ids = disabled_options.map(function(i,v) {
return this.value;
}).get();
//==================================
// Option-2:
//==================================
// Get Disabled options Ids Using SelectBoxID
var disabled_options_ids= $('#selectboxID option[disabled]').map(function(i,v) {
return this.value;
}).get();

Jquery Mulitple select field error

I have multiple select field each with multiple options.
So, by using jquery to get the respective selected options content, I would be able to get the selected option content. However, this work for the first select field. But, does not work for others. Others keep referencing the first select field selected options content, instead of it owns. Please guide me! Thanks!
My Select fields
<select id="resource_dd" name="resource_dd">
<option selected="selected" value="nil1">No resources.</option>
<option value="1">Week1</option>
<option value="2">Resource1</option>
</select>
<select id="module_dd" name="module_dd">
<option selected="selected" value="nil2">No restriction.</option>
<option value="1">IT1234</option>
<option value="2">IT2345</option>
</select>
Jquery to retrieve the selected content.
$("#module_dd").change(function ( event ) {
var option = $("this").children();
var module_id = $(option+":selected").val(); //module_id get 'nil1' as content instead of nil2
});
Just try this, it will give you the selected value.
$("#module_dd").change(function ( event ) {
var module_id = $(this).val();
});
First of all, you should be saying $(this) instead of $("this").
Second, $(event.target) is probably more appropriate here.
Third, using .children as in $(event.target).children(":selected") will get you what you want.
This is happening because you are referencing $("#module_dd").
You need to add another function and change that to $("#resource_dd") to get the other select field.
Problem code
var option = $("this").children();
var module_id = $(option+":selected").val();
You can't concat a selector string to a jQ collection object. You need to filter the option collection for those which are selected either by:
var option = $( this ).children(":selected");
Or
var option = $( this ).children();
var module_id = option.filter(":selected").val();
Please see Eli Courtwright's answer, but in addition to that, you should do something like $("select") or $("#module_dd, #resource_dd") to target both select fields.

Determining selected option using jQuery after using get() to retrieve the select

I have used get() to retrieve the first select drop down on the page like so:
styleSelect = jQuery('select').get(0);
And I can do normal things like
jQuery(styleSelect).remove();
To remove the select, but I'm having trouble finding the correct syntax to get the currently selected option's text. I've tried:
jQuery(styleSelect, ':selected').text();
and several variations of this, I think I'm just missing something dumb here.
jQuery('select').val()
should return the value of the currently selected element.
although, this does return the value. It is rare to return the text.
you could do it with something like the following:
jQuery('#test').change(function() {
//get text(), change to .val() to get value
var value = jQuery(':selected', this).text();
//insert value
jQuery('h2 span').html(value);
});
http://jsfiddle.net/pCsF9/
accompying html
<select name="test" id="test">
<option value="AA">AA</option>
<option value="MA">MA</option>
<option value="LA">LA</option>
<option value="GO">TEST</option>
</select>
<h2>selected:<span></span> </h2>
NOTE change .text() to .val() and select the last option to see the difference between selecting the value and text. the .text() should return TEST, where .val() will return GO
Here's the old-skool non-jQuery version that works in all scriptable browsers:
var option = styleSelect.options[styleSelect.selectedIndex];
alert("Value: " + option.value + ", text: " + option.text);
Use first the selector, then the context:
jQuery(':selected',styleSelect).text();
matchew's suggestion will work too but only when you didn't set the value-attributes of the <option>'s
(If you set the value-attributes you will get the value of the selected option instead of the text)
var styleSelect = $('select option:selected');
console.log(styleSelect.val());
Will give you the value of the option currently selected

Categories

Resources