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.
Related
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())
For example i have 2 records pre-selected as seen in screenshot below.
I noticed that aria-selected="true" for selected ones.
How can I find it by title and remove/reset it so it will not be part of current selected items.
Thanks in advance.
I think this should work:
$('#idSelect option[title="myTitle"]').first().remove();
Hope it helps.
select2 has link to particular <select> element in DOM. So, first you need to change select option, and then trigger change event of select2
For change option text you can like this
<select id="mySelect">
<option value="option1">Text</option>
</select>
var $select2 = $("#mySelect").select2();
$('#mySelect option[value="option1"]').text = 'Another text';
And then trigger change event for select2:
$select2.trigger("change");
Remove item
$('#mySelect option[value="option1"]').remove();
$select2.trigger("change");
Select one option
$select2.val("option1").trigger("change");
Select multiple options
$select2.val(["option1", "option2"]).trigger("change");
Remove one from selected
If you need remove one option from already selected, you need to get selected options, remove one, and set new options to select2.
var sel = $select2.val(); // array
sel.splice(sel.indexOf("option1"), 1);
$select2.val(sel).trigger("change");
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
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");
I have multiple dropdown menus that are the same, I need them to be the same.
<select name="Obrojgoluba" id="otacmajka" class="selectbox_dodajpostojeceg" onchange="dodajpostojeceg('otac')">
<option value="1">06557-07-681</option>
<option value="2">07216-05-552</option>
</select>
This is my jQuery function to get value from that select list
function dodajpostojeceg(x)
{
var ID = $('select[name="Obrojgoluba"]').val();
alert(ID);
}
But problem is that it gets value from the first select list, not from others I have on my site. When I click on the first one it gets good values. but when I click on other select list on my site that are the same as first one it returns or empty or value it remembered from the first select list
You are using this
var ID = $('select[name="Obrojgoluba"]').val();
And it is possible as you said that there are multiple select on your page. So if they are having same name, above code would select the first one and that is what you are getting.
So you can just change the function and markup to made this code workable.
function dodajpostojeceg(element)
{
var ID = $(element).val();
alert(ID);
}
and call this function as like this
<select name="Obrojgoluba" id="otacmajka" class="selectbox_dodajpostojeceg" onchange="dodajpostojeceg(this)">
JS Fiddle Demo
A strange thing to be doing, but try this:
function dodajpostojeceg(x)
{
var ID = $(this).val();
alert(ID);
}
As CBRoe comments, multiple identical IDs are invalid, and this may hamper your progress...
Make sure that the jquery lib is included and the function is defined before the html
<head>
function dodajpostojeceg(x)
{
var ID = $('select[name="Obrojgoluba"]').val();
alert(ID);
}
</head>
<body>
<select name="Obrojgoluba" id="otacmajka" class="selectbox_dodajpostojeceg" onchange="dodajpostojeceg('otac')">
<option value="1">06557-07-681</option>
<option value="2">07216-05-552</option>
</select>
</body>
Fiddle: http://jsfiddle.net/kR8yH/
When the html is rendered, it will look for a function named dodajpostojeceg() and if it not defined, it will not be able to bind the select and the function
I am assuming that all the selects are uniquely named