drop options in dropdown box - javascript

I am using 24 dropdowns. I want to select a driver for a position. But when i select a driver for the first position it should be removed from the other dropdowns so i can't use a driver two times. The dropdown is:
<select name="rijderQual1">
<option value="1">S. Vettel</option>
<option value="2">M. Webber</option>
<option value="3">J. Button</option>
<option value="4">L. Hamilton</option>
<option value="5">F. Alonso</option>
<option value="6">F. Massa</option>
<option value="7">M. Schumacher</option>
<option value="8">N. Rosberg</option>
<option value="9">K. Raikkonen</option>
<option value="10">R. Grosjean</option>
<option value="11">R. 11</option>
<option value="12">R. 12</option>
<option value="14">K. Kobayashi</option>
<option value="15">S. Perez</option>
<option value="16">R. 16</option>
<option value="17">R. 17</option>
<option value="18">P. Maldonado</option>
<option value="19">R. 19</option>
<option value="20">H. Kovalainen</option>
<option value="21">J. Trulli</option>
<option value="22">P. de</option>
<option value="23">R. 23</option>
<option value="24">T. Glock</option>
<option value="25">C. Pic</option>
</select>
The names are rijderQual1 to rijderQual24. So when i select S Vettel for example in rijderQual1 it should be removed from the 23 other dropdowns.
Is there a way to do this? I think it should be done with JS or jQuery?

You can iterate thru all options everytime some selected value is changed and hide the options that are selected somewhere else:
$('select').change(function() {
var selectedValues = $('select').map(function() { return this.value; }).get();
$('option').show();
$.each($('option'), function(i, item) {
if($(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 )
{
$(this).hide();
}
});
});​
DEMO

Try populating your dropdown box through an array, and on each item selected delete that item from that array. both JS and JQuery would work.

I still believe another approach would be wiser, for example colour-coding all dropdowns that have the same value selected. Or unselect the option from the first dropdown if you select it in another. That way you wouldn't deprive users from doing what they want, but warn them if they try to do something that's not allowed. Better for UX. Something a little more like this.
// Store text labels for options
$("option")
.each(function() {
$(this).data("label", $(this).text());
});
$('select').change(function() {
// Get selected values
var selectedValues = $('select').map(function() { return this.value; }).get();
// Reset conflicting dropdowns
currentVal = $(this).val();
$(this).siblings("select")
.each(function() {
if ($(this).val() == currentVal) $(this).val(0);
});
// Mark selected options as unavailable
$("option")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
$(this).text("(" + $(this).data("label") + ")");
else
$(this).text($(this).data("label"));
});
});​
DEMO: http://jsfiddle.net/NAWNP/
Still, according to your requirements this would iterate through the options, disabling those that are in use by other dropdowns. This way you can still see your options, even though you can't make them.
$('select').change(function() {
var selectedValues = []
$("option:selected").each(function() { selectedValues.push($(this).val()) });
$("option")
.removeAttr("disabled")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
{
$(this).attr("disabled", "true");
}
});
});​
DEMO: http://jsfiddle.net/ntxmh/2/

Working demo http://jsfiddle.net/zyGH7/
another http://jsfiddle.net/fLTxj/
Much concise version. This is the source: jQuery remove options except current (Very well written)
Hope it fits the cause! B-)
Code
$('document').ready(function() {
$(".hulk").change(function() {
var val = this.options[this.selectedIndex].value;
$('select').not(this).children('option').filter(function() {
return this.value === val;
}).remove();
});
});​

Related

2 identical select list, but don't allow the same values selected in them

Here i have the javascript code for my task: https://jsfiddle.net/gckkvLcv/4/
<select id="s1">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select id="s2">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>
I need to translate it to a jQuery version.
On a document load i can see the same values in a select lists. I need to disable that behavior.
Since you're using jQuery that could be done simply like :
$('.tracked_select').on('change', function() {
//Get selected options
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
//Disable the already selected options and enable others
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
});
Hope this helps.
trigger_chane();
$('.tracked_select').on('change', function() {
trigger_chane();
});
function trigger_chane(){
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="tracked_select">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select class="tracked_select">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>

Jquery filter is not working as expected

<div id="div1">
<input id="input1">
<select multiple="multiple" id="select1">
<option value="sandeep">sandeep</option>
<option value="ram">ram</option>
<option value="raj">raj</option>
<option value="pak">pak</option>
<option value="abc">abc</option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="journey">journey</option>
<option value="mahesh">mahesh</option>
</select>
</div>
<script type="text/javascript">
var selectClone1;
selectClone1 = $('#select1 option').clone();
$('#input1').on('keyup', function(){
$('#select1 option').remove();
var value = $(this).val();
selectClone1.filter(function(index, element){
console.log('index : '+index);
console.log('element : '+element);
return value == '' || element.value.indexOf(value) >= 0;
}).appendTo('#select1');
});
$('#select1').on('click', function(){
var option = $('option:selected', this).clone();
$('option:selected', this).remove();
selectClone1 = $.grep(selectClone1, function(el){return el.value == option[0].value}, true);
</script>
I am working on the search functionality along with removal of options when user clicked on option. The above code is working properly for search but when i clicked an option to delete from select box after search for a value, parameters of filter function(index, element) getting exchanged. Due to it error is coming. Can you help me guys where i am missing the point.
Better to use Array's splice method for removing element from main array and no need to clone.
$('#select1').on('click', function(){
var option = $('option:selected', this);
$('option:selected', this).remove();
selectClone1.splice($.inArray( option[0], selectClone1 ), 1);
});

Jquery dropdown, want one value always top when page loads

When the page loads i want to sort the dropdown using the jquery, to show the BI option first in the dropdown. I am generating the dropdown from the database.
<select id="conversionPixels" name="conversionPixels" >
<option value="10">PA3G ABTestConversion1DayWindow</option>
<option value="11">activ Conversion</option>
<option value="12">Proactiv Plus 24 Hour View</option>
<option value="13">Proactiv Plus Conversion</option>
<option value="0">BI</option>
</select>
I have used below jquery, it is not working
$("#conversionPixel").each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// Sort all the options by text. I could easily sort these by val.
$(this).html($("option", $(this)).sort(function(a, b) {
if( a.text=='BI'){
return -1;
}
if( b.text=='BI'){
return 1;
}
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
// Select one option.
$(this).val(selectedValue);
});
So why not to do something like
When you get data from database make sure BI is first Use code like
select id,name
from friends
order by id=5 desc, id asc
And then just use foreach to create options for your select - BI will be first
Use this code snippet:
$("#conversionPixels > option").each(function() {
if(this.text == "BI"){
$(this).remove();
$("#conversionPixels").prepend($(this));
}
});
This works if the select option text value you want to change is always BI.
//copy values BI
var html = $('select option').filter(function () { return $(this).html() == "BI"; }).html(),
value = $('select option').filter(function () { return $(this).html() == "BI"; }).val();
//remove option BI
$('select option').filter(function () { return $(this).html() == "BI"; }).remove();
//add to start copied value BI
$('select').prepend("<option selected value ='"+value+"'>"+html+"</option>");
If I understood your question correctly, all you want is the <option value="0">BI</option> element to be first on the select. Try runing the code snippet below.
$("#conversionPixels").children().each(function(index, elem) {
var $elem = $(elem);
if ($elem.val() === "0") {
$elem.remove();
$("#conversionPixels").prepend($elem);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="conversionPixels" name="conversionPixels">
<option value="10">PA3G ABTestConversion1DayWindow</option>
<option value="11">activ Conversion</option>
<option value="12">Proactiv Plus 24 Hour View</option>
<option value="13">Proactiv Plus Conversion</option>
<option value="0">BI</option>
</select>

Javascript / JQuery - Sorting by Multiple Classes

having a bit of trouble here, any help would be greatly appreciated...
I am trying to hide and show a bunch of list items based on several classes assigned to them.
In my JS Fiddle Example I have several items with classes relating to their description.
I have managed to hide and show these, but complex selections are not possible...
example: If I wanted to only see fabrics that are "premium", "blue" and "linen".
Something like this (that works lol) is what I am after...
$('.sel_range').click(function() {
range = document.getElementById("range").value;
if ($('.fabric_option').hasClass(range)) {
$('.' + range).fadeIn('fast', function() {
!$('.fabric_option').hasClass(range).fadeOut("fast");
});
}
});
Something like this should work
var selects = $('#range, #fabric, #colour');
selects.on('change', function() {
var el = selects.map(function(i, item) {
return item.value.indexOf('all_') === 0 ? '' : '.' + item.value;
}).get().filter(function(x) {
return x.length;
}).join('');
$('#fabric_options li').show().not(s?s:'*').hide();
});
FIDDLE
It starts with showing all the list items, then joins the values together to create a clas selector, leaving out the class if all_something is selected etc. and then hides everything that doesn't match, and if nothing is selected excludes everything.
I think it can be solved like this:
var range, fabric, colour;
var updateShown = function() {
$('li').show()
if (range) {
$('li:not(.' + range + ')').hide();
}
if (fabric) {
$('li:not(.' + fabric + ')').hide();
}
if (colour) {
$('li:not(.' + colour + ')').hide();
}
}
// Range
$('#range').change(function() {
range = $(this).val();
updateShown();
});
// Fabric
$('#fabric').change(function() {
fabric = $(this).val();
updateShown();
});
// Colour
$('#colour').change(function() {
colour = $(this).val();
updateShown();
});
With value="" of each select first option
<select id="range">
<option class="sel_range" value="">All Ranges</option>
<option class="sel_range" value="luxury">Luxury</option>
<option class="sel_range" value="premium">Premium</option>
<option class="sel_range" value="base">Base</option>
</select>
<select id="fabric">
<option class="sel_fabric" value="">All Fabrics</option>
<option class="sel_fabric" value="leather">Leather</option>
<option class="sel_fabric" value="linen">Linen</option>
<option class="sel_fabric" value="cotton">Cotton</option>
</select>
<select id="colour">
<option class="sel_colour" value="">All Colours</option>
<option class="sel_colour" value="red">Red</option>
<option class="sel_colour" value="blue">Blue</option>
<option class="sel_colour" value="green">Green</option>
</select>
jsFiddle demo
what about this?
$('#range').on('change',function () {
range = $("#range").val();
$('li').each(function(){
if(!$(this).hasClass(range)){
$(this).hide();
}else{
$(this).show();
}
});
});
// just for range, rest in fiddle
http://jsfiddle.net/J3EZX/6/
If you're using jQuery, just string them together with a . and no space, e.g.:
$(".linen.red.base").text("Help! I'm being replaced!");

Remove last selected element from the multiple select if user select more than 3 option using jquery

I need to select only 3 options from the multiple select. If user selects more than 3 options than the last selected element should be replaced by the new one clicked.
I have a example as follows:
<select multiple id='testbox'>
<option value='1'>First Option</option>
<option value='2'>Second Option</option>
<option value='3'>Third Option</option>
<option value='4'>Fourth Option</option>
<option value='5'>Fifth Option</option>
<option value='6'>Sixth Option</option>
<option value='7'>Seventh Option</option>
<option value='8'>Eighth Option</option>
<option value='9'>Ninth Option</option>
<option value='10'>Tenth Option</option>
</select>
When user selects
First option
Second option
Third option
Now he reaches max selection limit 3 .If he click on the another option like Tenth Option I need to remove Third option and get selected Tenth option
For that i tried this but no idea how I can achieve my goal
<script type="text/javascript">
google.load("jquery", "1");
$(document).ready(function() {
//alert("1111");
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
latest_value = $("option:selected:last",this).val()
alert(latest_value);
}
});
});
</script>
Please suggest some idea or solution.
This works quite nicely:
var lastSelected;
$("#testbox").change(function() {
var countSelected = $(this).find("option:selected").length;
if (countSelected > 3) {
$(this).find("option[value='" + lastSelected + "']").removeAttr("selected");
}
});
$("#testbox option").click(function() {
lastSelected = this.value;
});
I had to set a global variable lastSelected as well as an options click event to capture the actual last option clicked (this.value in the change event was giving me the top selected option, not the actual last option).
Demo: http://jsfiddle.net/JAysB/1/
Well, I don't like jQuery, so I've developed the same (fiddle), but in pure, vanilla, easy-to-read JavaScript:
document.getElementById('testbox').selopt=new Array();
document.getElementById('testbox').onchange=function(){
for(i=0; i<this.childNodes.length; i++)
if(this.childNodes[i].tagName!='OPTION')
continue;
else{
if(this.childNodes[i].selected &&
this.selopt.indexOf(this.childNodes[i])<0)
this.selopt.push(this.childNodes[i]);
}
if(this.selopt.length==4)
this.selopt.splice(2,1)[0].selected=false;
}
P. S. No global variables! :P
var lastOpt;
$('#testbox option').click(function () {
lastOpt = $(this).index();
});
$('#testbox').change(function () {
if ($('option:selected', this).length > 3) {
$(' option:eq(' + lastOpt + ')', this).removeAttr('selected');
}
});
JSFIDDLE

Categories