SELECTS: Hide the selected option on a secondary select - javascript

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

Related

Unable to deselect 'select multiple' options with selection counter and optgroups

I'm using the code from the accepted answer here
How do you limit options selected in a html select box?
to count the selected options in a 'select multiple' menu:
var last_valid_selection = null;
$("#select_options").change(function(event) {
if ($(this).val().length > 10) {
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
$("#select_options_text").text("Please select at least one, and up to ten options. You have currently selected "+$(this).val().length);
}
});
The menu is divided into six optgroups. When I hit 10 selections I can no longer make selections, as expected. But I can also no longer use CTRL+click on selected options to deselect them.
If I remove all optgroups, the menu functions correctly. It also functions correctly with one and two optgroups. It only seems to be when a third optgroup is added that the problem described above appears.
I have tested in Chrome and Firefox and the problem occurs in both.
Problem
You have duplicate options, so when try to restore the last selection by calling $(this).val(last_valid_selection), you could be selecting more than one value than you actually want (i.e. you end up selecting more than 10).
For example, you have more than one Biochemistry, so when last_valid_selection contains one instance of Biochemistry, all the duplicate Biochemistry options will be selected.
Solution
Use a different way of remembering the last valid selections.
Here I present a solution using data attribute and individually store whether or not an option has been previously selected.
function save_selected(select){
$(select).find("option").each(function(){
var t = $(this);
t.data("last-selected", t.is(":selected"));
});
};
function load_selected(select){
$(select).find("option").each(function(){
var t = $(this);
t.attr("selected", t.data("last-selected"));
});
};
$("#select_options").change(function(event) {
if ($(this).val().length > 10) {
load_selected(this);
} else {
save_selected(this);
}
});
Using this method, each individual option element has its own "last selected" state stored in its own data attribute. There would be no duplicate conflicts.
Demo: https://jsfiddle.net/alan0xd7/gzdrL5wu/12/

Don't show selected item in dropdown list

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/

print the count and the value of selected options inside a text box with jquery

i wanted to make a script to parse the count of selected options from a dropdown list.
I tried my code to jsfiddle but it doesnt work, even if i dont get any syntax error.did i do something wrong ?
$(document).ready(function(){
var count=$("#jform_params_foreignmanuf:selected").length;
$("#jform_params_manucounter").val(count);
});
http://jsfiddle.net/aewsduwo/22/ .
Also if i wanted to make a text area and print the value of the dropdown option?
$(document).ready(function(){
var $val= $("#jform_params_foreignmanuf:selected").val;
$("#jform_params_manucounter").val($val);
});
http://jsfiddle.net/pvpqd286/6/ i think this, for the first option in my example
<option selected="selected" value="127">1</option>
would ouput "127" instead of "1" that i want to print right?
Couple of things:
1) You need to escape special character present in id tag.
2) You need to find option by selected attribute and not select element as selected
$("#\\#jform_params_foreignmanuf :selected").length
Demo for selected option count
and for getting selected elements value in textbox as comma seprated string:
var count=$("#\\#jform_params_foreignmanuf").val().join(",");
$("#jform_params_manucounter").val(count);
Demo for selected value
Update: for getting first selected option text:
var firstselectedtext=$("#\\#jform_params_foreignmanuf :Selected:first").text();
$("#jform_params_manucounter").val(firstselectedtext);
Demo for first selected option text
for getting all selected options text:
var selectedtext=$.map( $('#\\#jform_params_foreignmanuf :Selected'), function (element) {
return $(element).text()
});
$("#jform_params_manucounter").val(selectedtext.join(','));
Demo for getting all selected options text
if i wanted to make a text area and print the value of the dropdown option?
Then you can do this:
$(document).ready(function () {
var $val = $('select[id="#jform_params_foreignmanuf"] :selected').text();
$("#jform_params_manucounter").val($val);
});
As your select element contains a special character of # so either you can escape it with \\ or you can make an attribute selector like above.
would ouput "127" instead of "1" that i want to print right?
For this you just need to use .text() instead of .val().
Checkout the demo.
You can try this one:
$("#jform_params_foreignmanuf").on('click', function(){
var count = $("#jform_params_foreignmanuf option:selected").length; //count selected options
$("#jform_params_manucounter").val(count);
var val= [];
$("#jform_params_foreignmanuf option:selected").each(function(){
val.push($(this).text()); //save each selected text in array
});
$("#jform_params_manuvalue").text(val.join(',')); //write selected text to textarea (comma-seperated)
});
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

custom select box- when selecting option value, show corresponding data-image as selected value

for this custom select box, what needs to be done to display an image which is associated to an option value in the select box placeholder.
http://jsfiddle.net/6eCFz/
in this code, how to use the data-attribute, first, to show an image associated with an option value as the selected value and second, to display tick marks when dropdown is opened to indicate the selected value.
Additionally, there are minor bugs:
a code for unique selection, for two select box filled with same options, does not seem to work.
$("#c_id1").change(function(){
$("#c_id2 option:hidden").show();
if($(this).val().length ){
$("#c_id2 option[value=" + $(this).val() + "]").hide();
}
});
$("#c_id2").change(function(){
$("#c_id1 option:hidden").show();
if($(this).val().length ){
$("#c_id1 option[value=" + $(this).val() + "]").hide();
}
});
http://jsfiddle.net/73epV/ - (vanilla script as proof-of-concept)
also, it does not ensures uniqueness onLoad
after triggering the dropdown, if mouse is moved away without first hovering over the option list, the dropdown does not close.
lots of love for any help :)
thanks

Categories