Jquery Chosen get the Id of un-selected value in dropdown - javascript

I have manage to get id of selected option for the Chosen plugin. Here is the jsfiddle Demo.
Now I am not sure how to get the Id of unselected option. I am using this code to get the id of selected option.
var SelectedIds = $(this).find('option:selected').map(function() {
if ($(this).attr('value') == params.selected)
return $(this).prop('id')
}).get();
alert(SelectedIds);

When an option is deselected, you get the change event, but the params object has a deselected property that you can use just like you're using the selected.
I made a jsfiddle for you to demonstrate: http://jsfiddle.net/1eut1c3d/
$("#chosen").chosen().on('change', function(evt, params) {
if (params.selected !== undefined) {
var selectedID = $(this).find('option:selected').map(function() {
if ($(this).attr('value') == params.selected)
return $(this).prop('id')
}).get();
alert("Selected: " + selectedID);
}
if (params.deselected !== undefined) {
var deselectedID = $(this).find('option').not(':selected').map(function() {
if ($(this).attr('value') == params.deselected)
return $(this).prop('id')
}).get();
alert("Deselected: " + deselectedID);
}
});

Related

Button is being disabled due to hidden select elements

I have a form with three select options:
Fit
Colour
Size
By default, the 'Fit' dropdown and 'Colour' dropdown are active with a default value selected (e.g. Regular Fit and Blue Colour).
There are three different 'Size' dropdowns, but only one is visible at any time depending on what is selected from the 'Fit' dropdown.
The Button is disabled if an option value="none".
Problem
The Button only becomes active if all three 'Size' dropdowns are altered so that their value is not "none" (this is done by selecting an initial size for Regular, and then selecting Petite and Long from the 'Fit' dropdown). Ideally, I only want the button to take into account the 'Size' dropdown that is active.
Update
Working jsFiddle solution provided by #nagappan below, big thanks.
https://jsfiddle.net/dodgers76/c0dvdwbz/
var currentSelectedVals = {'selector-fit':'','selector-color':'','selector-sizes':''};
var disableComboVals = [
{'selector-fit':'','selector-color':'','selector-sizes':'none'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'10'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'20'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'22'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'24'},
{'selector-fit':'long','selector-color':'','selector-sizes':'22'},
{'selector-fit':'long','selector-color':'','selector-sizes':'24'}
];
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});
};
$(function(){
var sizeVal = 'none';
$("select.selector-fit").on("change", function(){
//remove active
$("select.selector-sizes.active").removeClass("active");
//check if select class exists. If it does then show it
var subList = $("select.selector-sizes."+$(this).val());
if (subList.length){
//class exists. Show it by adding active class to it
subList.addClass("active");
subList.val(sizeVal);
}
});
$('.selector-sizes').on('change', function() {
sizeVal = $(this).val();
});
});
$(function() {
$('.selector').on('change', function() {
var $sels = $('option.selector-sizes:selected[value="none"]');
var isSizeSelector = jQuery.inArray( "selector-sizes",this.classList);
currentSelectedVals[this.classList[1]] = this.value;
console.log(currentSelectedVals);
var result = checkDisableCombo();
console.log(result);
if ( result.length > 0) {
console.log('disabled false');
$("#Testing").attr("disabled", true);
} else {
$("#Testing").attr("disabled", false);
}
}).change();
});
If we want to disable the button by combination of the drop down selected values. We can have a global variable to track the current selected values from three drop downs. Only we can have array of disbale combos. So whenever user select a value we cross check with disable combos and if it matches we can disable the button. Validate the combo can be done as below. Updated the jsfiddle link. JS FIDDLE UPDATED
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});

jQuery Multi-Select Listbox where 'None' Option Deselects All Others

Fiddle here: https://jsfiddle.net/q0o11c5e/17/
I have a Multi-Select Listbox with 'None' with the following requirements:
Selecting 'None' included anywhere in the selection => only 'None'
is selected (anything else is turned off)
Deselecting any other item
with Ctrl+click, if nothing else is selected, will automatically
select 'None'.
This is implemented with jQuery's Change function. My issues:
1) First of all, for #2 (Full Ctrl+click deselection): the flow doesn't come into the $( "#listbox" ).change(function() at all. You can see that because if you select 'A' and then deselect it with Ctrl+click, the Alert at the top of the function isn't displayed.
2) For #1, if the selection includes 'None' (value '') anywhere, I create a blank array, push '' onto it, and set the Listbox Val to it (and break immediately), but that doesn't work.
$( "#listbox" ).change(function() {
alert('SelArray: ' + $('#listbox').val() + ' Length: ' + $('#listbox').val().length);
// If no selection, automatically select 'None'
if ($('#listbox').val().length == 0) {
alert('Nothing selected');
}
else
{
// If new selection includes empty ('None'), deselect any other active selections
$.each($('#listbox').val(), function (index, value) {
if (value == '') {
alert('None selected, clearing anything else..');
var noneOnly = {};
noneOnly.push('');
$('#listbox').val(noneOnly);
return false;
}
});
}
});
If I get the intention correctly, something like the below?
$( "#listbox" ).change(function() {
var arr= $(this).val();
if (arr == null || arr.length === 0 || (arr.length > 1 && arr[0] === ''))
$(this).val(['']);
});
This simply sets the selection whenever no value is selected or when multiple values are selected including 'none'
Fiddle
$("#listbox").on("input change", function() {
if($(this).find("option[value='']:selected").length!=0 || $(this).find("option:selected").length==0) {
$(this).find("option").attr("selected", false);
$(this).find("option[value='']").attr("selected", true);
return false;
}
});
hi, check my above piece of code, this is my try https://jsfiddle.net/q0o11c5e/22/
(Posted on behalf of the question author).
This is solved now, final fiddle here: https://jsfiddle.net/q0o11c5e/23/
JS code:
$( "#listbox" ).change(function() {
var arr= $(this).val();
if (arr == null || arr.length === 0 || (arr.length > 1 && arr[0] === '')) {
$(this).val(['']);
}
else
{
// If new selection includes empty ('None'), deselect any other active selections
$.each(arr, function (index, value) {
if (value == '') {
var noneOnly = [];
noneOnly.push('');
$('#listbox').val(noneOnly);
return false;
}
});
}
});

jquery clone not working if user select other from the drop down the current text field disabled false

Working on jquery clone with my current code everthing works fine.
first scenario if user select other from the drop down the text
field gets enabled
Second scenario if user click addmore button div gets clone
perfectly with id when user select other both Original and clone
textfield gets enabled actually it should be only the cloned should
get enabled not the enabled
Here is the current Jquery code
var i=1;
$(document).on("click", ".edu_add_button", function () {
var i=$('.cloned-row1').length;
$(".cloned-row1:last").clone(true).insertAfter(".cloned-row1:last").attr({
'id': function(_, id) { return id + i },
'name': function(_, name) { return name + i }
}).end().find('[id]').val('').attr({ 'id': function(_, id) { return id + i }
});
$(".cloned-row1:last").find(".school_Name").attr('disabled', true).val('');
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
return false;
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row1').length;
if(len>1){
$(this).closest(".cloned-row1").remove();
}
});
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name").prop('disabled', false);
$(".school_Name").val('');
}else{
$(".school_Name").prop('disabled', true);
}
});
$(document).on('change', '.txt_degreName', function (){
var cur = $('.txt_degreName').index($(this));
$('.degree_Description').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$("#degree_Description").prop('disabled', false);
$("#degree_Description").val('');
}else{
$("#degree_Description").prop('disabled', true);
}
});
Here is the fiddle link
Kindly suggest me
thanks & regards
Mahadevan
DEMO
The issue comes be cause you are using class selector directly. You need apply value only to the text box which belongs in the same container. Use closest() to find the parent.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
var container = $(this).closest('.container-fluid');
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name", container).prop('disabled', false);
$(".school_Name", container).val('');
}else{
$(".school_Name", container).prop('disabled', true);
}
});
DEMO HERE
You need to refer proper element that has to be disabled and enabled.
Take the sibling of select's parent and find the input element to be disabled as below:
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$(this).closest('.col-xs-6').next('.col-xs-6').find('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', false);
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").val('');
}else{
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', true);
}
});
From what you did, you actually change every fields with class .school_Name, to achieve what you want you can add $(this).parents(".row").find(".class_name") so it only change the current div.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).parents(".row").find(".school_Name").prop('disabled', false);
$(this).parents(".row").find(".school_Name").val('');
}else{
$(this).parents(".row").find(".school_Name").prop('disabled', true);
}
});
DEMO HERE
You can do it this way with targeting specific item using parent() and next() selector and also i prefer to access specific field instead of index(such as eq) for input.
var schoolObj = $(this).parent().next().find(".school_Name");
schoolObj.val($(this).val());
if ($(this).val() == "other") {
schoolObj.prop('disabled', false);
schoolObj.val('');
} else {
schoolObj.prop('disabled', true);
}
Here is the Fiddle
You can have a look for jquery traversing:
parent: https://api.jquery.com/parent/
Next: https://api.jquery.com/next/
Find: https://api.jquery.com/find/
and for full traversing: https://api.jquery.com/category/traversing/

Making a dropdown find() faster

I have a dropdown box and an input that is used to autofilter the dropdown.I need to make a dropdown filtering faster. I've added a textbox before the dropdown menu and an event to filter the dropdown:The code snippet is:
td.prepend(' <span class="ms-metadata"><br/>(type some chars to filter )</span><br/>');
.....
td.prepend($('<input/>', {id: 'DPFilter',
onkeyup: 'filterDP(this)'
}));
and on the function filterDP(element) :
....
var value = $(element).val();
$( dropdown).find("option").each(function() {
var optionValue = $(this).val();
$(dropdown).find('option[value="' + optionValue + '"]').map(function () {return $(this).parent('span').length === 0 ? this : null;})
.wrap('<span>')
$(this).map(function () { return $(this).parent('span').length === 0 ? this : null;}).wrap('<span>').hide();
...
if ((value == "") || ($(this).text().search(value) > -1) ){
$(dropdown).find('option[value="'+optionValue+'"]').show();
}
The only place I can think of, is the $(dropdown).find('option[value="'+optionValue+'"]').show(); , instead of finding it, to use an index, but I don't know how.
Also, I use the find() twice (in a code not shown), will a variable making faster?
Thank you
You can both simplify and speed this up by using filter:
var value = $(element).val();
$(dropdown).filter(function() {
if ($(this).text().indexOf(value) != -1) {
$(this).show();
}
});

How to append and remove checkbox values to and from hidden field

I am trying to append selected checkbox values to the hidden field.
But I am only successfull in adding only one checkbox value at this time.
Is there anyway to append selected checkbox values in hidden field.
function CheckBox_Clicked(item) {
if (item.checked == true) {
$('#Chkboxvalue').val($(item).val());
}
}
I don't know if I could use jquery append function here.
Thanks
Please use below javascript
function CallOnEachCheckBoxChangeEvent(){
var selectedCheckBoxesValue = '';
$('#DIVID').find("input:checkbox.CheckBoxClassName:checked").each(function (i, selected) {
if (selectedCheckBoxesValue.length == 0) {
selectedCheckBoxesValue += $(selected).val();
}
else {
selectedCheckBoxesValue += ',' + $(selected).val();
}});
//Set the value of hiddenField selected checkboxes value
$(hiddenFieldValueId).val(selectedCheckBoxesValue);
}
$('#Chkboxvalue').val($('#Chkboxvalue').val()+' '+$(item).val());
There is an easier way to do that.
$('input[type="checkbox"]:checked').map(function() {
return $(this).val();
}).get().join();
Demo : http://jsfiddle.net/codef0rmer/EWsMX/

Categories

Resources