Remove working on JQuery options, Hide does not? - javascript

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

Related

Hide either one of the option by selected value in javascript?

I have a form with two identical select lists like follows:
<select id="system" name="system[1][1]">
Option 1
Option 2
Option 3
</select>
<select id="system" name="system[1][2]">
Option 1
Option 2
Option 3
</select>
I want the user select either one of this select option2. If user choose option2 in first select then hide the option2 in second select and vice versa.
Example:
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
Which I think is bit of messy. Is it any elegant way that I can achieve this in Javascript or Jquery?
Thanks
Try following code :
<select id="system" name="system[1][1]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<select id="system" name="system[1][2]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
jQuery :
jQuery('select').change(function(e){
var value = $(this).val();
var selectboxId = $(this).attr('name');
jQuery('select option').show();
if(selectboxId == 'system[1][1]') {
jQuery('select[name="system[1][2]"]').find('option[value="'+value+'"]').hide();
} else if(selectboxId == 'system[1][2]') {
jQuery('select[name="system[1][1]"]').find('option[value="'+value+'"]').hide();
}
});
Try this Check out this fiddle
I hope this is what ur looking for ?
Html
<select id="system1" name="system[1][1]">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="system2" name="system[1][2]">
<option value="1">1</option>
<option value="2">2</option>
</select>
Jquery
$(document).ready(function(){
$('select').change(function(){
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select1.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select2.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
});
});
I'd suggest the following approach (note the change of id properties, this is not optional, it's required in order to have valid HTML):
// cache the relevant <select> elements, here we use
// a CSS attribute-selector to get those <select>
// elements whose id attribute begins with 'system':
var selectElements = $('select[id^=system]');
// binding the anonymous function as the event-handler
// for the 'change' event, using the on() method:
selectElements.on('change', function() {
// we retrieve the index of the selected option from
// the changed <select> element:
var chosen = this.selectedIndex;
// we hide all the previously-selected <select> elements:
selectElements.hide()
// we find the <select> element at the same index as
// the chosen <option>:
.eq(chosen)
// and then show that element:
.show();
})
/* This is just to give a visual cue to
show which of the elements is currently
visible on the page: */
#system1 {
box-shadow: 0 0 1em fuchsia;
}
#system2 {
box-shadow: 0 0 1em limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="system1" name="system[1][1]">
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="system2" name="system[1][2]">
<option>Option 1</option>
<option>Option 2</option>
</select>
JS Fiddle demo.
References:
CSS:
Attribute selectors.
JavaScript:
HTMLSelectElement.selectedIndex.
jQuery:
on().
although there are some answers, here's what i came up with:
$("select").on("change", function() { //on any change event in all selects
var currentSelection = $(this); //save the used select box
//then take all selects, except the activated one, take the 'option' childs and iterate through them
$("select").not(currentSelection).find("option").each(function() {
if ($(this).val() == currentSelection.val()) //if option value = chosen value
$(this).hide(); //hide it
else //if not
$(this).show(); //show it (to reshow already hidden elements)
});
});
this works with endless options! but as soon, as you have more then 2 selects, you have to rework the 'show' part of this script...
here's a working fiddle: https://jsfiddle.net/usksL955/1/

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

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('');
});
}
});

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

How to filter a select box by data-attributes?

I am trying to filter a select box person by data-attributes selected in another select box invoice_project_id:
HTML:
<select id="invoice_project_id">
<option value="1">Project A</option>
<option value="2">Project B</option>
<option value="3">Project C</option>
</select>
<select id="person">
<option data-project_ids="[1,2]">Spencer, Eve</option>
<option data-project_ids="[3]">Goodwin, Alisha</option>
<option data-project_ids="[]">Emard, Tito</option>
<option data-project_ids="[2,3]">Bergstrom, Damien</option>
</select>
Javascript:
function filterOption(id) {
return $('#person option').filter(function () {
return $.inArray(id, $(this).data('project_ids')) > -1
});
}
$('#invoice_project_id').on('change', function () {
var project = $('#invoice_project_id').val();
$('#person option').hide();
filterOption(+project).show();
});
I also built a fiddle.
The problem is that it's not working in Safari and Chrome. I am new to jQuery and basically copied & pasted the code together.
Can anybody tell me how to get it working?
Thanks for any help.
Hiding options is not cross browser compatible, so clone the options are try
function filterOption($opts, id) {
return $opts.filter(function () {
return $.inArray(id, $(this).data('project_ids')) > -1
});
}
var $person = $('#person'),
$popts = $person.children();
$('#invoice_project_id').on('change', function () {
var project = $('#invoice_project_id').val();
filterOption($popts.clone(), +project).appendTo($person.empty())
}).change();
Demo: Fiddle

jQuery - Restore the removed select option

I have multiple dropdown menus with the same options. If one option was selected, other dropdown menus will not show the selected option. When I tried to reset the selected option, it did not restore the removed select option.
HTML part:
<select id="selectNumber" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="selectNumber2" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Javascript part:
$(".selectbox").change(function(){
var selectedIndex = $(this).index();
var myVal = $(this).val();
$(".selectbox").each(function(i){
if (selectedIndex != i){
$("option", this).each(function(){
if (myVal == $(this).val() && myVal != 0){
$(this).detach();
}else{
$(this).prepend();
//not work
}
});
}
});
});
the demo but not working
Thanks for your time.
This should do what you want
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
var myVal = $(this).val();
if (myVal !='0') {
$selects.not(this).children('[value="'+myVal+'"]').remove();
}else{
var replaceVal=$(this).data('currVal');
$selects.not(this).append( $opts.filter( '[value="'+replaceVal+'"]').clone())
}
$(this).data('currVal', myVal);
});
DEMO http://jsfiddle.net/7Ssu7/8/
EDIT Version - keeps sort order
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
/*create array of all selected values*/
var selectedValues=$selects.map(function(){
var val=$(this).val();
return val !=0? val :null;
}).get();
$selects.not(this).each(function(){
var $sel=$(this), myVal=$sel.val() ||0;
var $options=$opts.clone().filter(function(i){
var val=$(this).val();
return val==myVal || $.inArray(val, selectedValues) ==-1;
});
$sel.html( $options).val( myVal)
});
});
DEMO: http://jsfiddle.net/8uunN/1/
When you do a detach(), the object is removed and needs to be put into a "global" variable to save as a reference.
For your purpose, you can use .hide() and .show() as it retains the object in the list, without causing a DOM insertion or removal (so definitely better for performance).
Well, your current code is not work, because you are not store selected value in another dropdown list. Also, like others said, use hide and show instead of detach and prepend.
You can see my solution in jsfiddle (tested in firefox)

Categories

Resources