How to get value of deselected option? - javascript

Suppose I have a select like this:
<select id="cars" multiple>
<option value="1">Ferrari</option>
<option value="2">Lamborghini</option>
</select>
Imagine now that both values are selected, I deselect Ferrari, how can I retrieve the value of the deselected option, so in this case Ferrari?
I tried with:
$('#cars option').on('click', function(){
console.log($(this).val());
});
but the event is never fired, I also tried with change, this is fired, but I get only the selected values not the deselected one.

You could incorporate the usage of a class to track on change which elements are selected, and inversely which ones are no longer selected.
var $cars = $('#cars').on('change', function(){
// find the options that were selected, but are not now
var $deselected = $cars.find('option.selected:not(:checked)');
// add the selected class to the selected options for tracking
$cars.find('option:checked').addClass('selected');
// remove the selected class to untrack them
$deselected.removeClass('selected');
// report which options were deselected
console.log($deselected.get());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars" multiple>
<option value="1">Ferrari</option>
<option value="2">Lamborghini</option>
</select>

Related

javascript Trying to copy database generated text in selectbox to textbox

I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});

How to make a drop-down which give output on every onchange event

I am working on a Drop Down Select element which have 3 options lets name it as X,Y,Z having values 1,2,3 respectively.Now my question is to how to set a conditions or what to do next to show graph every time when i select option as earlier it only shows the graph of first option which i select first because of onchange function occured already.
Try this code. This will give you current option selected, based on which you can perform your next operations.
HTML:
<select id="select" onchange="onOptionChange();">
<option value="1">X</option>
<option value="2">Y</option>
<option value="3">Z</option>
</select>
JS:
function onOptionChange() {
console.log($('#select').val()); //prints current option selected
}
<select id="ddrp1">
<option value="">Select an option</option>
<option value="1">X</option>
<option value="2">Y</option>
<option value="3">Z</option>
</select>
Assuming an id for dropdown select is ddrp1.
$("#ddrp1").on("change", function() {
var selectedVal = this.value;
var selectedText = this.options[this.selectedIndex].text;
var selectedVal = $(this).find(':selected').val();
var selectedText = $(this).find(':selected').text();
// set your condition here based on selectedText or selectedVal to display graph
}​​​​);​

selectmenuchange appending object list only on first event

I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.
SCRIPT
$("#parent").selectmenu();
$("#members").selectmenu();
var allMembers = $('#members option'); // keep object list of all of the options for the select menu
$("#parent").on("selectmenuchange", function() {
var someMembers = [];
var id = $('#parent option:selected').data('id');
allMembers.each(function() {
if ($(this).data('parent-id') == id) {
someMembers.push($(this))
}
});
$('#members').empty().append(someMembers);
});
At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.
I can't figure out if this is a problem with selectmenuchange or empty().append()
HTML
<select name="members" id="members">
<option data-id="101" data-parent-id="1">Name1</option>
<option data-id="102" data-parent-id="1">Name2</option>
<option data-id="103" data-parent-id="1">Name3</option>
<option data-id="104" data-parent-id="2">Name4</option>
<option data-id="105" data-parent-id="2">Name5</option>
<option data-id="106" data-parent-id="3">Name6</option>
<option data-id="107" data-parent-id="3">Name7</option>
</select>
<select name="parent" id="parent">
<option data-id="1">Parent1</option>
<option data-id="2">Parent2</option>
<option data-id="3">Parent3</option>
</select>
Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:
$('#members').html(someMembers).selectmenu('destroy').selectmenu();
DEMO
Instead of selectmenu('destroy') and re-initializing the select menu you can also use selectmenu('refresh'). Refreshing sounds nicer than destroying it each time.
I have updated the fiddle of Guruprasad Rao with the refresh:
fiddle

Hierarchical Select List using jQuery

I have two select list,
Select list 1 contains the Mobile phone brands names
<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>
</select>
Select list 2 contains the phone type like
<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>
</select>
My quest is I want to display Select list 2 according to the value users select in Select List 1.
If a user selects Nokia in first selection, then only Lumia phones should be shown in second select list. Like so, for other phones.
When None is selected in First select list, then second select list should not show anything, but still visible without any option (like disabled button).
How can I accomplish this using jQuery?
The JSFiddle I have made from above select list.
I'd suggest:
/* select the select element whose name is "mobile-phone",
assign an event-handler for the 'change' event:
*/
$('select[name="mobile-phone"]').change(function () {
// get the relevant/selected brand-name:
var brand = this.value;
/* find the option elements inside of the select element with
name="mobile-model", enable them all:
*/
$('select[name="mobile-model"] option').prop('disabled', false)
// show them all:
.show()
// filter the collection, to find only those whose value does not start with the brand-name:
.filter(function () {
return !(this.value.indexOf(brand) === 0);
})
// disable those elements:
.prop('disabled', true)
// hide them:
.hide();
});
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
filter().
hide().
prop().
show().
I think you are looking for:
$("#sel2").prop("disabled", true);
$( "#sel1" ).change(function() {
var value = $(this).val();
$("#sel2").prop("disabled", false);
$("#sel2 > option").hide();
$("#sel2 > option[value*='" + value +"']").show();
});
Only I put to selects Id for do the selection by Jquery more easy. Before I disabled the control wating for any selection, and when the first select change only I keep the option that macth with option[value*='" + value +"']".
Live demo here
There is a jQuery plugin that handles this exact case very nicely: http://www.appelsiini.net/projects/chained .
You should consider having two MySQL tables: brand, model. The brand table would just be a list of brands with IDs. The model table would contain a brand column where you input those IDs.
Then you should do a JSON query for the brand selected, and return a select list accordingly.
By doing it this way, you'll have an in depth database that you can call and manipulate in numerous ways.
Alternatively, you could do something like:
$(".mobile-phone").on("change", function(){
var brand = $(this).val();
$("[data-brand]").hide();
$("[data-brand="+brand+"]").show();
});
And do this:
<option data-brand="Nokia" value="...

In Jquery Chosen plugin remove selection if user selects a particular value

I have the following multi select and I am using Jquery Chosen plugin
<select multiple="multiple" class="chzn-select span3" name="requestCategory" id="requestCategory">
<option selected="selected" value="">All</option>
<option value="2">Electrical</option>
<option value="4">Emails</option>
<option value="3">Filming Permits</option>
<option value="10">test1</option>
</select>
Client wants to make sure that i do not allow user to select ALL if any other value is selected or if user selects any other value then automatically deselect/remove ALL; because ALL = all categories so having individual option does not make sense. How do i do this?
Check if more than one item is selected, or if only one item is selected that it is not the first one - in these cases disable All.
$('.chzn-select').on('change', function() {
var selectedOpts = $('option:selected', this);
if(selectedOpts.length > 1 || selectedOpts.first().index() !== 0) {
$('option', this).first().attr('disabled', 'disabled');
}
});​
http://jsfiddle.net/zCk2z/5/
at first change of option [simple] removes the All category.
but i recomand to disable the item, it looks better use .attr('disabled', 'disabled') instead of .remove();
$('#requestCategory').change(
function(){
$(this).find('option:contains("All")').remove()
})

Categories