Get Value of Disabled Option in Select Multiple Jquery - javascript

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

Related

JQuery - Clone a select element, filter desired option elements and append to another select

I am working on a web page of an application on which there are two select elements (among other). Initially, both select elements will have values. Note specially that second select element will have full set of values to begin with. The requirement is for the content of second select to reduce to a subset based on what user has select in the first select element. Since I need to retain the initial content of the second select, I first clone it in document.ready().
Let us say following is the initial second select element
<select id="sid">
<option value="0" selected="">Unknown</option>
<option value="1">Unit</option>
<option value="2">House</option>
<option value="3">Apartment</option>
</select>
How could I create a clone and remove 'Unknown' and 'Apartment' from the object and append it back to the select having run empty() to clear the options first.
So far I have come with following. Looking for some information what could go in the function passed to filter (see comment //need logic to filter option with value Unknown and Apartment)
var toRetain = $('#sid').clone();
$('#sid').empty();
var secondClone = toRetain .clone()
$('option', secondClone).each(function(i){console.log(i));}); // able to print all options
$('option', secondClone).filter(function(i){
//need logic to filter option with value Unknown and Apartment
}).remove()
$('#sid').append(b.html())
Assuming the options you want to remove are always in the same positions you could use :eq() to select and remove them, no need to empty() the entire set:
var $toRetain = $('#sid').clone().removeAttr('id').appendTo('body');
$toRetain.find('option:eq(0), option:eq(3)').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sid">
<option value="0" selected="">Unknown</option>
<option value="1">Unit</option>
<option value="2">House</option>
<option value="3">Apartment</option>
</select>
Alternatively you could use :first and :last, or even add a specific class on them to select by. In any case the pattern would be the same; identify the option to be removed and call remove() on them.
If you need to select them by their text content then you can do that using filter():
let toRemove = ['Unknown', 'Apartment'];
var $toRetain = $('#sid').clone().removeAttr('id').appendTo('body');
$toRetain.find('option').filter((i, el) => toRemove.indexOf(el.textContent.trim()) != -1).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sid">
<option value="0" selected="">Unknown</option>
<option value="1">Unit</option>
<option value="2">House</option>
<option value="3">Apartment</option>
</select>
Also note that I used removeAttr() to remove the id from the cloned content, as id attributes must always be unique within the DOM.
Following code too achieves the desired
var toRetain = $('#sid').clone();
$('#sid').empty();
var secondClone = toRetain .clone()
$('option', secondClone).each(function(i){console.log(i));}); // able to print all options
$('option', secondClone).filter(function(i){
return ['Unknown', 'Apartment'].indexOf($(this).html()) != -1;
}).remove()
$('#sid').append(b.html())

how to disable order for input and options in selectize

I am using selectize0.11.0. I have a multiple <select>.
I need to do this.
Disable order for input of selectize.
Disable order for options.
First I select multiple option, and then I sumbmit the form.
Suppose: I select third and then I select first.
The <input> of selectize should be [third first].
When I resubmit the form without changing anything, the page after refresh would not change the order of options in <select> and texts in <input>.
The select code:
<select id="id_sel" multiple='multiple'>
<option selected='selected' value='1'>first</option>
<option value='2'>second</option>
<option selected='selected' value='3'>third</option>
</select>
What I tried:
$('#{{ filterform.plf.auto_id }}').selectize({maxItem:2});
plf_sel = $('#{{ filterform.plf.auto_id }}')[0].selectize;
plf_sel.clear();
plf_sel.clearOptions();
plf_sel.renderCache['option'] = {};
plf_sel.renderCache['item'] = {};
plf_sel.addOption(plf_sel_option);
plf_sel.setValue(plf_sel_option[0].value);
//plf_sel.setValue(plf_sel_option[1].value);
I lost a value, since setValue only set one value to be selected.
I put it on jsfiddlejsfiddle, but It can not simulate submit. how to do that?
Thanks.
Well, I change setValue() to addItems() to solve that problem, since setValue() clear all items first and then add item by calling addItems() once.

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

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

Selecting first option of multiple select elements by Prototype JS

I want to select first option of all the select dropdowns having class required-entry in a page with Prototype JS. I have searched through SO questions and found many relevant questions but not what I exactly needed.
Thanks
It's been quite a while since I've done any Prototype.js. So this may not be the best way to go about it, but it should work.
let's say you have a page with:
<select class='required-entry'>
<option value='a'>AAA</option>
<option value='b'>BBB</option>
<option​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ value='c'>CCC</option>
</select>
<select class='required-entry'>
<option value='x'>XXX</option>
<option value='y'>YYY</option>
<option value='z'>ZZZ</option>
</select>​
You can grab the first option for each select by doing:
var firstOptions = [];
$$('.required-entry').each(function(sel, i) {
firstOptions.push($(sel).getElementsBySelector('option')[0]);
});
// firstOptions is now an array containing the first options
Now, I couldn't tell from your question if you wanted to retrieve the first options, or set the select value so that the first option is literally selected. Here's the later:
$$('.required-entry').each(function(sel, i) {
sel.selectedIndex = 0;
});

JS/Jquery: how to check whether dropdown has selected values?

I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>
Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
var hasValue = ($('select > [selected]').length > 0);
Alternatively,
var hasValue = $('select').has('[selected]');
Quick solution:
<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>
Then see if you have a .val()
The approved answer doesn't seem to work for me.
Here is how I do it to check if all select options are selected:
if($('select option:selected').length > 0) {
/* Do your stuff here */
}
As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first option.
See, for example, the result of
$('option:selected')
on your first example.
If you really want to prevent this happening, you have two options. The first is to introduce a new, empty element into the select, per Jason's answer. The other option is to deselect the automatically selected value:
$(document).load(function(){
$('option:selected').attr('selected', false);
});
This clears the selection. Any result of $('select').val() that isn't an empty string will therefore be a change by the user.

Categories

Resources