Select2 dropdown to show "x selected" on third selected item - javascript

The following code uses select2 to allo multiple selection from a dropdown. My question is how can I show a "x selected" after third choice, instead of all the choices and have a huge textbox?
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
$("#e1").select2();
I have a jSfiddle here
http://jsfiddle.net/ishanbakshi/fyhsz9ra/

I have worked hard and managed to supply a jQuery solution for you. Change your JavaScript to this:
$("#e1").select2();
$(document).ready(function(){
var showHugeSelect = false;
$("#s2id_e1 ul.select2-choices").prepend("<button id='btnE1ShowAll' style='display: none;' />")
$("#btnE1ShowAll").click(function(e){
$("#s2id_e1 .select2-search-choice").show();
$("#btnE1ShowAll").hide();
showHugeSelect = true;
function hideHugeSelect(){
showHugeSelect = false;
}
setTimeout(hideHugeSelect, 5000);
})
setInterval(customizeSelectE1, 500);
function customizeSelectE1(){
var selectedCount = $("#s2id_e1 .select2-search-choice").length;
if(selectedCount > 2 && !showHugeSelect){
$("#s2id_e1 .select2-search-choice").hide();
$("#btnE1ShowAll").html(selectedCount + " selected").show();
}
}
})
I've checked it in the jsFiddle and it works perfectly. It's not possible to make a more elegant solution. If you really want a more elegant one, you need either to develop your own control or change the source code of Select2.

I have created a fiddle . Try this way..
$("#e1").select2().on('change', function() {
if ($(this).val().length >= 3) {
var html = $('.select2-choices li:first-child').clone();
$('.select2-choices li:not(:last-child)').remove();
var divContent = html.find('div').html($(this).val().length + ' Selected');
$('.select2-choices').prepend(html).find('a').on('click', function() {
$(this).parent('li').remove();
$("#e1").val('');
});
}
});

Related

Remove working on JQuery options, Hide does not?

Got this HTML:
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Iterating over the options with this javascript & jQuery:
var departmentDDL = $(row).find('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
$(this).remove(); // this works
}
});
I'm trying to hide the options, not remove them. Why does one work and not the other?
You have an extra ( in your if, remove it, it will work but only in Chrome with a little buggy behavior.
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function() {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3" >DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Note that hiding HTML options has several issues cross browser and won't give expected results in some browsers, for further details check How to hide a <option> in a <select> menu with CSS?
remove extra ( here if (($(this)[0] and it will work
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}else{
$(this).parent().val($(this).val()).change();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
It selected in the else part

Novice Javascript query

I have a very simple question, I have tried searching forums but I've not been able to find what I think I need. Below is a bit of script which works as I expect:
$(function(){
var ProjType = $("#cfs_i3_cf3");
$(ProjType).change(function() {
$("#cfs_h3").css("background-color", "red");
alert('okay then!');
});
});
Basically, the ID #cfs_i3_cf3 represents a drop-down box and when it changes, the colour changes.
I want to advance this a little and say:
If #cfs_i3_cf3 = A then color = X otherwise color = Y
Very simple, but struggling with the syntax and hopefully it's a very simple answer as I'm not used to javascript.
Many thanks in advance!
James
The correct approach to do this is:
You listen for changes in the select box and then on its change get the select box's value and if it is one then color the paragraph red else yellow.
$(function(){
var ProjType = $("#cfs_i3_cf3");
$(ProjType).change(function(){
if($(this).val() == "1")
{
$("#cfs_h3").css("background-color", "red");
}
else
{
$("#cfs_h3").css("background-color", "yellow");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cfs_i3_cf3">
<option value="" selected disabled>Select</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<p id="cfs_h3">THIS IS THE OUTPUT</p>
Just to add additional refactor. Sorry! I simply think jQuery is doing to same thing but why load extra library?
function switchColor(select){
var redOrNot = select.value == 'red' ? true: false;
var el = document.getElementById('cfs_h3');
if (redOrNot) {
el.style.backgroundColor = select.value;
} else {
el.style.backgroundColor = select.value;
}
}
/* if you don't need logic, you can simply do
el.style.backgroundColor = select.value; since the color logic
is already embedded in the HTML.
*/
<select id="cfs_i3_cf3" onchange="switchColor(this)">
<option value="" selected disabled>Select</option>
<option value="red">One</option>
<option value="yellow">Two</option>
</select>
<p id="cfs_h3">THIS IS THE OUTPUT</p>

jquery.sumoselect not showing checkboxes

I have the following code, which fetches data dynamically and shoves it into a sumoselect.
<select id="geoSel_location_2">
</select>
<script type="text/javascript">
jQuery(document).ready(function() {
var returnSelect = jQuery('#geoSel_location_2');
returnSelect.SumoSelect({placeholder: 'All Suburbs'});
jQuery.getJSON("/cfcs/system.cfc?method=getSelectsRelated&returnformat=json&queryformat=column",{"type":"location","id":4,"index":2},function(res,code) {
if(res.ROWCOUNT > 0){
for(i=0; i<res.ROWCOUNT; i++){
var val = res.DATA.OPTION_VALUE[i];
var text = res.DATA.OPTION_TEXT[i];
returnSelect[0].sumo.add(val,text);
};
};
});
})
</script>
The options load beautifully, but the multi-select checkboxes are not showing next to each option. I thought they showed by default.
The jsfiddle is a simplified version of the above.
JSFIDDLE
OK, duh, the solution is to add "multiple="multiple", i.e.
<select "multiple="multiple" id="geoSel_location_2">
<option value="1">Auckland</option>
<option value="2">Wellington</option>
<option value="3">Christchurch</option>
<option value="4">Dunedin</option>
</select>

Disable the Drop down options

I want to disable the drop down options based on the condition. I want to disable all the other options except the option which has the text "Java".
Ex:
<select id="ddlList">
<option value="csharp">C#</option>
<option value="vb">VB.NET</option>
<option value="jquery">jQuery</option>
<option value="java">Java</option>
</select>
In this case Only java option should be enable and others should be disable.
JQuery :
$('#ddlList option:not([value=java])').prop('disabled', true);
JSFiddle
JavaScript :
var filter = document.querySelectorAll('#ddlList option:not([value=java])')
Object.keys(filter).forEach( function(g){ filter[g].disabled = true })
JSFiddle
function optionDisable(selectId, optionIndex){
document.getElementById(selectId).children[optionIndex].disabled="disabled";
}
or
document.getElementById(optionid).style.display = 'none';
or
function makeDisable(){
var a=document.getElementById("ddllist")
a.disabled=true
}
Use the disabled property.
$("#ddlList option[value!='java']").prop("disabled", true);
If you want more control, in a more practical way, you can go over each option:
$("#ddlList option").each(function () {
var allowed = ["java"];
if (allowed.indexOf($(this).val()) === -1) {
$(this).prop("disabled", true);
}
});
You can write your code like this:
Select Language: <select id="ddlList">
<option value="csharp">C#</option>
<option value="vb">VB.NET</option>
<option value="jquery">jQuery</option>
<option value="java">Java</option>
</select>
JavaScript:
$(document).ready(function(){
var condition = true;
if(condition)
{
$("select option").prop('disabled',true);
$("select option[value='java']").removeAttr('disabled');
$("select").val("java")
}
else
{
//apply your logic here
}
});
Demo Fiddle
$("#ddlList option").each(function(){
if(!$(this).val().contains("java"))
$(this).attr('disabled', true);
});
This code lets you set the disabled attribute of each dropdown option by checking if its value contains "java"
JSFIDDLE DEMO

option is still visible in select after remove()

Hi all I have two select fields, on select field first if user select option value one or two then in select field of second all options are visible but if it select option two in first then option two want to remove from select id second. Following is my code:
<script type="text/javascript">
var index3,str;
</script>
<select id="first" onchange="chk();">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<select id="second">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<script type="text/javascript">
function chk()
{
index3 = document.getElementById("first");
str= index3.options[index3.selectedIndex].value;
alert("str:"+str);
if (str=="two")
{
$("#second option[value='two']").remove();
}
else
{
if ( $("#second option[value='two']").length == 0 )
{
$("#second").append('<option value="two">two</option>');
}
}
}
</script>
In fiddle it works fine here, But on mobile problem is: If I select option two from select id second, and then select option value two in first select id, then also option two is visible in second select id, if I click on second select id then only it removes. But in jsFiddle it works perfect. Any suggestion will be appreciated, Thanks in advance.
Here i have done complete bin for above issue. please go through demo link.
Demo http://codebins.com/bin/4ldqp7p
HTML
<select id="first">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
<select id="second">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
jQuery
$(function() {
$("#first").change(function() {
var optVal = $(this).val().trim();
if (optVal == "two") {
$("#second").find("option[value=" + optVal + "]").remove();
} else {
if ($("#second").find("option[value=two]").length <= 0) {
$("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));
}
}
});
});
Demo http://codebins.com/bin/4ldqp7p
check this Edit
$('#first').change(function() {
$("#second option[value='" + $(this).val() + "']").remove();
});
Your code looks a bit odd overall. If your intention is to remove the item from 'second' if it is selected in 'first', try this update: http://jsfiddle.net/NWbXt/58/
$(function() {
var first = $('#first'),
second = $('#second'),
removed;
first.change(function() {
var selected = first.val();
second.append(removed); //.. add back old option
removed = second.find('option[value="' + first.val() + '"]').remove();
}).trigger('change');
});​

Categories

Resources