Don't show selected item in dropdown list - javascript

I have a select2 dropdown with a few values (let's say colors), and I want to remove from the dropdown list the current selected item. For example, if all the options are
white, green, red, blue
and the current selected item is white, if the user clicks on the dropdown, he'll only see the other 3 colors (green, red and blue).
Now, I can easily remove the currently selected item with jquery, and restore it back on change, but that really doesn't feel clean.
Is there any built-in method for doing that, or at least a method that is a little bit more "cleaner"?

Remove An options:
$("#selectBox option[value='White']").remove();
Add an options:
$("#selectBox").append('<option value="greed">Green</option>');

use .hide() to hide it or use a custom class with display: none; and add it to the option.
$(".selector option[value=white]").hide()
For cross-browser support, disable it instead of hiding it.
$(".selector option[value=white]").prop("disabled", true)

You can use :selected from the jQuery library.
( "select" )
.change(function() {
var str = "";
$( "select option:selected" ).each(function() {
(select option:selected).text() = " ";
});

You can use the templateResult option to customize options you see in the dropdown. This can also be used if there are certain options you don't want to display.
You pass a javascript function as the value of the templateResult option. Example:
$('#color').select2({
templateResult: formatColorOption
});
Before calling .select2() on your select element, you first need to define the formatColorOption() javascript method. Example:
function formatColorOption (color) {
if (!color.id) { return color.text; }
// this next line prevents the currently selected option from showing up in the dropdown list
if ($('#color').find(':selected').val() == color.element.value) { return null; }
// otherwise display the name of the color
return color.text;
};
To see a fancy example that combines TemplateResult with some other options, check out the JSFiddle.
https://jsfiddle.net/vatdoro/4xu6vcc5/

Related

How to set the value of a select box when it is enabled only?

I have a top level select box that when a user makes a selection here, I want this value to be used for all the below select boxes relating to this top level box.
The problem I am having is that, if any one of the lower select boxes is disabled, I want the above process to ignore this select box as it has already been assigned a value.
Obviously, if the lower select box is enabled then I want to assign the top select value to it.
To disable the select list based on a particular value, I have used:
$("select[name=f03]").eq(index).attr('disabled', 'disabled');
Here is the jQuery that I have used but is not working:
var top_select = $("select[name=f07]").val();
$("select[name=f03]").each(function(index){
if $("select[name=f03]").eq(index).is(':enabled'){
$("select[name=f03]").eq(index).val(top_select);
}
});
From this code, it is the lower selects ([name=f03]) that I am trying to set only when it is enabled.
First I would disable select like this:
$("select[name=f03]").eq(index).prop('disabled', true);
Second, your function should be much simpler:
$("select[name=f03]").each(function(){
if ($(this).prop('disabled')) return;
$(this).val(top_select);
});
you should use jquery :enabled selector as follow
$("select[name=f03]:enabled").each(function(){
//execution
});
or
$("select[name=f03]:enabled").val("value");
here is jsfiddle example http://jsfiddle.net/kso2oqr5/1/
When you are disabling elements use .prop(property,value)
var top_select = $("select[name=f07]").val();
$('select[name="f03"]').val(function(){
if(!this.disabled){
return top_select;
}
});
DEMO

Jquery change() dont work on select box when contain only one item

I'm working on a dynamic select box with php and jquery, i have 4 select boxes, the content of the first one is loaded in the page load.
When i choose one of the items in the first select box, the seconde one get data from database related to the first select box...and so on
But the problem is : when the select box contain only one item, the change() function of jquery doesn't work $('#MySelectId').change(function(){ //......});
Any suggestions ?
I'm working with PHP, jQuery v1.6.4 and jQuery Chosen Plugin.
If your select box only contains 1 item this item is already selected so if you select it again the value doesn't change so no change event is fired. Add a placeholder like "Please select item" or something which is selected by default.
Try something like
$('#MySelectId').on('change', 'select', function() {
alert('changed');
}).click(function(){
if($('#MySelectId select option').length == 1) {
$('#MySelectId select').change();
}
});
Fiddle
or you can try with jquery bind if you are not using 1.7.x + version.
$('#MySelectId').bind('change', function() {
alert('changed');
}).click(function(){
if($('#MySelectId select option').length == 1) {
$('#MySelectId select').change();
}
});
test here
check this post also

SELECTS: Hide the selected option on a secondary select

I have two select with the same elements (options) in it.
What I am trying to do is that when the user select a value from the first select box, the second select box hides that option, and automatically select the first visible option if the selected option was the same as the one in the first select.
I know that :first selects the first element of a group of "objects", and that :visible only select the "visible" ones, so i was thinking that using :first of :visible should work, but what I am getting is no selection at all.
if I remove the :visible it works unless the second select box has the first element selected, and the user selects the first element on the first select box
This is what I have so far, please keep in mind that I have tried :first and :visible in any combination, but I really think that the problem here is that "hide hasn't finished its job when I use :visible
$('#style_position').change(function(){
var sel_pos_id = $(this).val();
var sel_xtr_pos_id = $('#style_position_extra').val();
$('#style_position_extra option[value=' + sel_pos_id + ']').hide().siblings().show();
if(sel_pos_id==sel_xtr_pos_id){
$('#style_position_extra option')
.removeAttr('selected')
.filter(':visible') //I also tried find(':visible')
.filter(':first') //I also tried find(':first')
.attr('selected','selected');
}
});
Here's one method
/* cache a set of options from second select*/
var $opts=$('#style_position_extra option').clone();
$('#style_position').change(function(){
var sel_pos_id = $(this).val();
/* find matching option copy*/
var $newOpts=$opts.filter(function(){
return this.value !=sel_pos_id;
}).clone();
/* replace exisiting options with match*/
$('#style_position_extra').html( $newOpts);
});
Here's another possibly simpler one
$('#style_position').change(function(){
var selected=$(this).find('option').not(':selected').clone();
$('#style_position_extra').html(selected);
});
Thanks to charlietfl I figured out, here is the final answer:
$('#style_position').change(function(){
var sel_pos_id = $(this).val();
var sel_xtr_pos_id = $('#style_position_extra').val();
var selected=$(this).find('option').not(':selected').clone();
$('#style_position_extra').html(selected)
if(sel_pos_id!=sel_xtr_pos_id){
$('#style_position_extra option[value=' + sel_xtr_pos_id + ']').attr('selected','selected');
}
});
This code will automatically select a different option if the two selects have the same option, or it will keep the same option selected in the second selectbox

How to trigger an event ONLY if both dropdowns are selected?

I have a dropdown select list on my page of class="TypeFilter".
I have a jQuery event that fires when a value in that list is selected.
$(".TypeFilter").change(function()
{
// Extract value from TypeFilter and update page accordingly
));
I now have to add another list to the page, and I want to implement functionality which will prevent the .change(function() from running unless both are selected.
In both lists the first option in the list is some text instructing the user to select one of the items, so I was thinking of just writing some logic to test that both lists have a selected index greater than 0.
I think this is a touch unclean though, especially considering that other pages that have a TypeFilter use the same logic.
Is there any nifty functionality in jQuery that can do this?
edit I should specify that the user needs to be able to update the page by selecting either dropdown, so I can't put the onchange on the second element and test that the first element has a selected value, as suggested in one of the answers
If you bind the same event to all dropdowns, you can get a collection of all the dropdowns and check that all of them are selected. Example:
$('.Dropdown').change(function(){
var elements = $('.Dropdown');
if (
elements.filter(function(){
return this.selectedIndex > 0;
}).length == elements.length
) {
// all dropdowns are selected
}
});
As you partly mention, put the onchange on the second element and test that the first element has a selected value before you fire off any logic.
Use bind instead, and as the eventdata, send a function that checks that either that both are selected or that the other is selected. Untested code:
function checker() {
// test your conditions
}
$(".TypeFilter").bind('change', {test: checker}, function(event)
{
if (event.data.test && event.data.test()) {
// Extract value from TypeFilter and update page accordingly
}
));
This way the other pages that use the same function will not notice any changes.

jQuery UI multiple selections

see this demo from jquery ui
you have to hold down the Ctrl key to make multiple selections
I really like the code but I don't want to force my visitor to press ctrl key
I want the code to allow multiple selections without holding ctrl key
is this possible?
I asked you a questions in the comments but I'll just write up a simple selection solution so you can see what I was thinking.
So basically you can use the jquery toggle() effect to roll your own selector. When a user clicks you'll add the orange class, when he clicks again it will remove the orange class.
$(document).ready( function() {
$('ul#selectable li').toggle( function() {
$(this).addClass('orange'); }, function() {
$(this).removeClass('orange'); } );
});
Then all your job is to grab all the li elements with the orange class and post them to a form or whatever your end goal is. Haven't checked this code but what your doing is asking for all the li elements within selectable that have the orange value at the end of the class attribute.
With the code below I'm creating a new array and then adding the text() value of each "orange li" into it.
var theSelections = new Array();
$('ul#selectable li[class$="orange"]').each( function(i) {
theSelections[i] = $(this).text();
});
Yes. However, the implementation would have to allow selected items to be deselected when clicked on a second time. You would just need to modify the code slightly to achieve this.
Do a .selectable( 'Enable' ) on all the items.
Then you will need to do a .selectable( 'toggle' ) onClick on all items.
That should do the trick.

Categories