I have 2 multi selects in a page, and I need to transfer some of the option in first into second, while mantaining the search capabilities.
The problem is, that when I use the search input, it restores the selects to their original options...
Here is the jquery search function:
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
Here is the js fiddle : http://jsfiddle.net/C2XXR/ !
*I believe the problem lies in the options variable, but have no idea on how to solve it *
Thanks!
I have updated the fiddle. http://jsfiddle.net/C2XXR/2/
I have updated the code for right and left transfer. You have to change the option array itself got the filter, adding them in the dom will not work. In the changed code one issue is once we add from right to left or left to right it is getting added in the last position of the target select.
Please check and let me know if this is what you want.
Below is the main changed function. Later you can create a common function i suppose. Code can be optimized more.
$('[id^=\"btnRight\"]').click(function (e) {
var selected = $(this).parent().prev('select');
var target = $(this).parent().next('select');
target.find('option[value="999"]').remove()
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#isselect_code');
selected.data('options', tempOption);
});
$('[id^=\"btnLeft\"]').click(function (e) {
var selected = $(this).parent().next('select');
var target = $(this).parent().prev('select');
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
if( tempOption.length == 0 )
{
// add 999 here
}
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#canselect_code');;
selected.data('options', tempOption);
});
the problem with your code is that after you click btnRight or btnLeft your collection of options for each select is not updated, so try after click on each button to call your filterByText as the following :
$('[id^=\"btnRight\"]').click(function (e) {
$(this).parent().next('select').find('option[value="999"]').remove()
$(this).parent().prev('select').find('option:selected').remove().appendTo('#isselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).parent().next('select').find('option:selected').remove().appendTo('#canselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});
Related
I developed the store locator using open street map and leaflet. The problem is when I want to type in searchbox it will become lagging to finish the word. That store locator read from the CSV file that has 300++ data. Below is the code for the searchbox:
var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
$("#storeinfo").hide();
if (map.hasLayer(circle)) {
map.removeLayer(circle);
}
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');
function setActive(el) {
var siblings = listings.getElementsByTagName('div');
for (var i = 0; i < siblings.length; i++) {
siblings[i].className = siblings[i].className
.replace(/active/, '').replace(/\s\s*$/, '');
}
el.className += ' active';
}
function sortGeojson(a,b,prop) {
return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}
storesData.on('ready', function() {
var storesSorted = storesData.toGeoJSON();
//console.log(storesSorted);
var sorted = (storesSorted.features).sort(sortGeojson)
//console.log(sorted);
storesSorted.features = sorted;
//console.log(storesSorted)
stores.addData(storesSorted);
map.fitBounds(stores.getBounds());
toggleSearch.onclick = function() {
//var s = document.getElementById('searchbox');
//if (s.style.display != 'none') {
//s.style.display = 'yes';
//toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
//$("#search-input").val("");
//search.collapse();
//document.getElementById('storeinfo').style.display = 'none';
//$('.item').show();
//} else {
//toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
//s.style.display = 'block';
//attempt to autofocus search input field when opened
//$('#search-input').focus();
//}
};
stores.eachLayer(function(layer) {
//New jquery search
$('#searchbox').on('change paste keyup', function() {
var txt = $('#search-input').val();
$('.item').each(function() {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
I dont know what is the cause of the lag in the search box. It is something wrong in code or the csv file? Thank you
Every iteration of $('.item').each is causing a layout change because $(this).hide() or $(this).show() causes the item to removed/added to the DOM as the style is set to display:none back and forth. DOM manipulations and the corresponding layout changes are expensive.
You can consider accumulating the changes and doing one batch update to the DOM using a function like appendChild
I'm using Isotope to function as a categorical organizer of linked content in a fancy layout. I'm trying to push multiple values into an array so it'll display all items touched by the filters. The end result is, however, just displaying the latest item in the array instead of the sum total. Initially, I was pushing all my values into a string, then declaring x as the final result-- I realize this isn't the way to go about this, and have since modified it. Instead of a string, I'm pushing into an array, and hoping to join each value so they'll all be displayed. However, I'm still getting nothing more than the latest selected value. JS as it stands below.
// store filter for each group
var filters = {};
$('.filters').on('click', '.button', function() {
var filters = [];
// var filters = '';
var selected = $(this).data('selected');
var group = $(this).data('group');
var currentFilter = $(this).data('filter');
// toggle function along with having multiple selectors
if(selected == "0") {
filters.push($(this).data('filter'));
filters = filters.join(', ');
// filters = $(this).data('filter');
$(this).data('selected', "1");
$(this).addClass('is-checked')
}
else {
$(this).data('selected', "0");
$(this).removeClass('is-checked')
}
// set filter for Isotope
$grid.isotope({
filter: filters
});
// flatten object by concatting values
function concatValues(obj) {
var value = '';
for (var prop in obj) {
value += obj[prop];
}
return value;
}
});
}());
I've also set up a codepen for fiddling. Thanks for any suggestions that come. Even pointing me to documentation or tutorials I may have missed would be a great help. For now, I'm studying this jsfiddle that does what I'm shooting for, to see how I can modify my code to better suit what's going on here.
Last week I also spend crazy time with this. :) Luckly I found Desandro's codepen http://codepen.io/desandro/pen/owAyG/
Hope that helps.
$( function() {
// filter functions
var filterFns = {
greaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt( number, 10 ) > 50;
},
even: function() {
var number = $(this).find('.number').text();
return parseInt( number, 10 ) % 2 === 0;
}
};
// init Isotope
var $container = $('.isotope').isotope({
itemSelector: '.color-shape',
filter: function() {
var isMatched = true;
var $this = $(this);
for ( var prop in filters ) {
var filter = filters[ prop ];
// use function if it matches
filter = filterFns[ filter ] || filter;
// test each filter
if ( filter ) {
isMatched = isMatched && $(this).is( filter );
}
// break if not matched
if ( !isMatched ) {
break;
}
}
return isMatched;
}
});
// store filter for each group
var filters = {};
$('#filters').on( 'click', '.button', function() {
var $this = $(this);
// get group key
var $buttonGroup = $this.parents('.button-group');
var filterGroup = $buttonGroup.attr('data-filter-group');
// set filter for group
filters[ filterGroup ] = $this.attr('data-filter');
// arrange, and use filter fn
$container.isotope('arrange');
});
// change is-checked class on buttons
$('.button-group').each( function( i, buttonGroup ) {
var $buttonGroup = $( buttonGroup );
$buttonGroup.on( 'click', 'button', function() {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$( this ).addClass('is-checked');
});
});
});
This is the solution I ended up with.
I came up with a separate solution but this is a great pen. I wish I had seen it before.
$(document).ready(function() {
// init Isotope
var $grid = $('.grid').isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows',
fitRows: {
gutter: 27
}
});
// store filter for each group
var filters = [];
$('.filters').on('click', '.button', function() {
var filterstring = '';
var selected = $(this).data('selected');
var currentFilter = $(this).data('filter');
// toggle function along with having multiple selectors
if (selected == "0") {
filters.push( currentFilter );
$(this).data('selected', "1");
$(this).addClass('is-checked')
} else {
$(this).data('selected', "0")
$(this).removeClass('is-checked')
var filtername = $(this).data('filter')
var i = filters.indexOf(filtername)
filters.splice(i, 1)
}
filterstring = filters.join(', ');
// set filter for Isotope
$grid.isotope({
filter: filters.join("")
});
});
});
I hacked an isotope combofilter with checkboxes, but here is the problem with the isotope items; They are disappearing when resizing browser window.
I dont why they are not displaying when I change the size of the browser!
Please so help!!
Normaly I use isotope V2. Here in JSFiddle, there is np with the window resizing however I used isotope v1..
I am driving crazy, when items disappeared I need to trigger by clicking a select button, then its going fine.
var $containerii;
var filters = {};
jQuery(document).ready(function () {
var $containerii = $('.isotope').isotope({
itemSelector: '.isotope-item'
});
getContent: '.isotope-item li'
var $filterDisplay = $('#filter-display');
$containerii.isotope();
// do stuff when checkbox change
$('#options').on('change', function (jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$containerii.isotope({ filter: comboFilter });
$filterDisplay.text(comboFilter);
});
});
function getContent() {
var items = document.getElementById("containerii")
}
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).removeAttr('checked');
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.siblings('input.all').attr('checked', 'checked');
}
}
}
If your using isotope v2, try this:
var $containerii = $('.isotope').isotope({
itemSelector: '.isotope-item',
isResizeBound: true
});
v1.5, this:
ADDENDUM
I don't see anything disappearing, just the col-md-10 shifting down when you resize your window. I changed the layout to avoid the shift and it seems to resize as it should.
jsfiddle
Thank you so much for helps and valuable responses. Finally I solved my problem by using trigger isotope on window resize at the end of the code.
$(window).on('resize', function () {
$containerii = $('.isotope');
triggerIsotope();
});
Ill post an image to explain it better.
So, imagine that I make a 1st search, then I make a 2nd, or 3rd, 4th..search and I want to back to my old searches.
I already have some code that saves old searches (working fine). My only problem is how to assign the values to a combobox in order to comboboxes return to an old state.
How could I start doing this?
edit:
$('#combos').on('change', '.combo', function() {
var selectedValue = $(this).val();
if (selectedValue !== '' && $(this).find('option').size() > 2) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[value="' + selectedValue + '"]').remove();
$('#combos').append(newComboBox);
}
});
var check_combo_box_values = $('#combos .combo').map(function ()
{
return $('option:selected', this).map(function() {
return parseInt(this.value);
}).get();
}).get();
I made a fiddle how to add options to a combobox
http://jsfiddle.net/hRQqp/2/
Since you stated you had no troubles with saving the old searches, you should be able to put the pieces together
var dropdown = document.getElementById('dropdown');
var list = [
"first",
"second",
"third"
];
// remove old options
while (dropdown.length> 0) {
dropdown.remove(0);
}
// add new ones
for (var i=0;i<list.length; i++) {
var option = document.createElement("option");
option.textContent = list[i];
option.value = i;
dropdown.appendChild(option);
}
I have a fiddle here: my fiddle. What I am trying to do is create a list of items from a separate group of lists. I cannot seem to get a grasp on what I am doing wrong, but here is whats happening:
I have a group of lists based on tabular data
Each list has the name of the column and a selection checkbox
If I select an item, it needs to be added to the selected columns area (vertical list)
There are 14 unique tabular items with checkboxes
(PROBLEM -->) When I select an item, it gets added 14 times in the selected columns section
code
(html):
I tried ti insert HTML but is not working right. Please look at the fiddle listed above.
(jquery):
var dte = // drag table elements
{
init: function() {
var chkbx = $('.group input[type="checkbox"]:checkbox');
//var chkbx = $('#accordion');
for (var i = 0, ii = chkbx.length; i < ii; i++) {
$(chkbx).bind("click", dte.adjustList);
}
},
adjustList: function(event) {
var list = [];
var str = '';
var eleval = event.currentTarget.value;
var eleid = event.currentTarget.id;
if (eleval == 1) {
list.push(eleid);
str = '<li>' + eleid + '</li>';
}
$('#vertical ul').append(str);
/*
//var ele = event.currentTarget.id;
var allVals = [];
var str = '';
//var obj = $("#"+ele);
var ele = $('#accordion');
$(obj+': checked').each(function(){
allVals.push($(this.val()));
dte.list.push($(this.val()));
str += '<li>'+$(this.val())+'</li>';
});
$('#verticle').text(str);
alert('List: ' + toString(list));
*/
}
};
dte.init();
init: function() {
$('.group input:checkbox').bind("click", dte.adjustList);
},
you only need to bind once based on your selector.
init: function() {
var chkbx = $('.group input[type="checkbox"]:checkbox');
$(chkbx).bind("click", dte.adjustList);
},
fiddle
I have edited your fiddle, I removed the for loop. Here is the link updated fiddle
You only need to bind the click event once.
You are binding events multiple time. You can do something like this:
init:function(){
$('.group input[type="checkbox"]:checkbox').bind('click',dte.adjustList);
},
Edited your fiddle:
http://jsfiddle.net/emphaticsunshine/tPAmc/