I have a multiple select like the following.
But what I now need is to display it like a normal "dropdown" select, because there are many normal selects on my website and it looks very strange if theres a select with size more than 1.
So the multiple select should also look like here.
I don't want to include an extra jQuery plugin or something else. I look for a easy html/css/js solution.
What you ask for is simply not possible. Your target look is a select box rendered by the web browser. You simply can not modify a multiple select to be rendered the same way. How would the user select multiple items?
For usability reasons I strongly suggest looking at another solution. Multiple selects are really hard for users to understand. A far more usable solution would be to use a group of checkboxes.
Or as WebAIM states it:
It is recommended that multiple select menus be avoided. Not all browsers provide intuitive keyboard navigation for multiple select menus. Many users do not know to use CTRL/Command or Shift + click to select multiple items. Typically, a set of check box options can provide similar, yet more accessible functionality.
More regarding usability and multiple select, see for example :
http://www.90percentofeverything.com/2008/12/03/multiple-select-controls-must-evolve-or-die/ or
http://alistapart.com/article/sensibleforms
This being said, there are multiple libraries which creates a custom experience, such as https://github.com/bsara/multi-select-dropdown.js (no dependency)
I made a quick class (pure JavaScript) that should behave as you wish. You'll probably want to add some more functionality.
EDIT: Updated the code, forgot you wanted a dropdown
https://jsfiddle.net/xLtfsgbd/1/
( function()
{
var MultipleSelectDropDown = function()
{
// constructor
}
MultipleSelectDropDown.prototype =
{
options: [],
selected: [],
size: 0,
displayed: false,
add: function(element)
{
this.options.push(element);
this.size = this.size + 1;
},
remove: function(element)
{
for(var stored in this.options)
{
if(this.options[stored] == element)
{
this.options.splice(stored, 1);
this.size = this.size - 1;
break;
}
}
},
render: function(onIdSelector)
{
var container = document.getElementById(onIdSelector);
if(typeof container == 'undefined')
{
window.alert('The list container is undefined!')
return;
}
var mainDiv = document.createElement('div');
mainDiv.setAttribute('style', 'width:300px; height: 50px display:block;');
var firstItem = document.createElement('div');
firstItem.setAttribute('style', 'width:250px; height:25px;');
firstItem.appendChild(document.createTextNode(this.options[0]));
var dropDownArrow = document.createElement('img');
dropDownArrow.setAttribute('src', 'https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-down-128.png');
dropDownArrow.setAttribute('style', 'width:25px; height:25px;');
_self = this;
dropDownArrow.onclick = function(e)
{
if(_self.displayed)
{
_self.displayed = false;
var displayedList = document.getElementById('daList');
document.body.removeChild(displayedList);
}
else
{
var rect = this.getBoundingClientRect();
_self.renderList(rect.left, rect.top);
_self.displayed = true;
}
};
firstItem.appendChild(dropDownArrow);
mainDiv.appendChild(firstItem);
//mainDiv.appendChild(dropDownArrow);
container.appendChild(mainDiv);
},
renderList: function(x, y)
{
var div = document.createElement('div');
div.setAttribute('id', 'daList');
div.setAttribute('style', 'positon:absolute; top:'+y+'; left:'+x+'; height:100px; width:200px; overflow-y:scroll; background-color:#fff;');
var list = document.createElement('ul');
var _self = this;
for(var stored in this.options)
{
var option = this.options[stored];
var listItem = document.createElement('li');
listItem.setAttribute('index', stored);
listItem.appendChild(document.createTextNode(option));
listItem.onclick = function(e)
{
var index = this.getAttribute('index');
if(index < 0 || index > _self.size)
{
return;
}
var selected = this.getAttribute('selected');
// Item not selected
if(selected == null || selected == '' || selected == 'false')
{
this.setAttribute('selected', 'true');
this.setAttribute('style', 'background-color:#0099ff;');
selected.push(option);
}
else // Item selected
{
this.setAttribute('selected', 'false');
this.setAttribute('style', 'background-color:#fff;');
for(var sel in _self.selected)
{
if(_self.selected[sel] == option)
{
_self.selected.splice(sel, 1);
}
}
}
};
list.appendChild(listItem);
}
div.appendChild(list);
document.body.appendChild(div);
}
}
SelectDrop = MultipleSelectDropDown;
})();
Related
so I'm using this code, to slideToggle a box on my webpage.
// OPEN CERTAIN BOX
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
var id = ('1');
var div = ('#toggle-content-' + id);
var img = ('#toggle-img-' + id);
var toggler = ('toggler-' + id);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
As you can see, I'm using the var id, to use the toggle function for a certain box, which has its own css and html code.
I have 7 more boxes. Until now, i copied the code 7 times and changed the id at each copy from 2 - 8. Is there a way to make it with one code?
I tried a for loop, that goes from 1 - 8 but this obviously didnt work.
Has someone an idea? Or do I have to make that 8 copies and changed the id.
Edit:
My approach with the for-loop:
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
for(i = 1; i <= 8; i++){
var id = (i.toString());
var div = ('#toggle-content-'+id);
var img = ('#toggle-img-'+id);
var toggler = ('toggler-'+id);
$( div ).hide()
$( toggler ).click(function(){
if (sliding == false){
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
...
And this is my html code for one box:
<tr><td cellspacing="0" cellpadding="0" height="50px" class="upper">
<toggler-1><area-head-text><img id="toggle-img-1" src="images/box_opener.png"/>Starterpaket</area-head-text></toggler-1>
</td></tr>
<tr><td>
<div id="toggle-content-1">
<area-head-text>
<img class="text-image" src="images/arrow.png"/>3 individuelle Entwürfe<br>
<img class="text-image" src="images/arrow.png"/>3 Korrekturzeichnungen<br>
<img class="text-image" src="images/arrow.png"/>Internationale Nutzungsrechte<br>
<img class="text-image" src="images/arrow.png"/>400€<br><br>
</area-head-text>
</div>
</td></tr>
I'm not sure why you put "Obviously" a loop doesn't work, because that's pretty much exactly what you should do. Something like this:
for(var i = 1; i <= 8; i++)
{
var div = $('#toggle-content-' + i);
var img = $('#toggle-img-' + i);
var toggler = $('toggler-' + i);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
}
This is 2 options.
(and my preference) -
Instead of using an ID to add the click event onto each individual toggle button, use the same class on each, and add the click event on that class. When the user clicks a toggle button traverse the DOM from the clicked toggle button to perform your toggle on the relevant <div>.
This would look something like:
$(function() {
$('.toggleBtn').click(function() {
var sliding = $(this).data('sliding'); //use data attr to store sliding status
if (sliding == false) {
$(this).data('sliding') = true;
}else {
return; //don't toggle we're sliding
}
// navigate to element and toggle
$(this).parent('.someParentElement').children('.theDiv').slideToggle(time,"swing");
//clear sliding status
$(this).data('sliding', false);
}
}
The reason this is my preference, is because although it's faster to target an ID for a click event than a class for a single event, using 7 click events on 7 different IDS in my opinion (I don't know for sure) is less efficient than using a single click event on 1 class. That's my perceived purpose of using events on classes rather than IDS.
Also this way, when you want to add another box in, or remove a box, you don't need to modify any Javascript, the only thing you would need to maintain this code for is if you decide to change the structure of the HTML, and therefore the navigation of the DOM to perform your toggle.
using your method:
var ids = ["id1","id2","id3"];
for(var id in ids) {
var $div = $('#toggle-content-' + id);
var $img = $('#toggle-img-' + id);
var $toggler = $('toggler-' + id);
$div.hide()
$toggler.click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$div.slideToggle(time,"swing");
// ...
}
I have pasted the javascript below but also a link to my codepen so you can see exactly what I am talking about.
I would like the heading to be clicked and expose the text below. On another click I would like for the text to go back to hidden. Multiple headings can be opened at the same time. What is happening with my current setup is you can click once to show, click again to hide and then when you click again to show nothing shows, if you keep clicking the text and headings below are eaten/dissapear. I would prefer to do this without jquery. thanks for any help.
http://codepen.io/jrutishauser/pen/YPrrNa
var clickToShow = function () {
if (this.nextElementSibling.className === 'open'){
this.nextElementSibling.remove('open');
} else if (this.nextElementSibling.className != 'open') {
this.nextElementSibling.className = 'open';
}
};
var articleHeadings = document.getElementsByTagName('h3');
for (var index = 0; index < articleHeadings.length; index++){
articleHeadings[index].onclick = clickToShow;
}
var subArticleHeadings = document.getElementsByTagName('h4');
for (var index2 = 0; index2 < subArticleHeadings.length; index2++){
subArticleHeadings[index2].onclick = clickToShow;
}
Change this.nextElementSibling.remove('open') to this.nextElementSibling.className = ''. I believe remove() method removes the element, not the class.
You can do it like this also. This is the correct way of doing it.
var clickToShow = function () {
element=this.nextElementSibling;
if (element.className === 'open'){
element.className=element.className.replace('open','');
} else if (element.className != 'open') {
element.className = 'open';
}
};
I would like to perform the following actions on my DOM:
Filter a list via multiple controls (combined):
Checkboxes
Select boxes
Free text input (like e.g http://vdw.github.io/HideSeek/)
So for example, the user can select a city from the select box, which filters the displayed items. When typing into the input field, the filter from the select is still in place, further filtering the displayed items by the entered text.
I normally write something by hand to combine multiple choices from different select boxes, but it's not ideal. Also, for a "free text" filter, I have always used jQuery-Plugins, and they tend to reset the selection when you start typing.
With tables, I use the datatables plugin, which brings along multiple filters. It's extremely feature-rich, but also quite heavy - and designed for tables, not for any type of lists.
What are the general recommendations / outlines on how to achieve this?
PS: Here's how I do it now. a) it's extremely proprietary and b) I haven't managed to combine it with a text filter yet:
function showItems(selectedCanton,showTypeOne,showTypeTwo){
var typeOneSelector = '';
var typeTwoSelector = '';
if (selectedCanton=='all'){
var cantonSelector = '';
}
else {
var cantonSelector = '.list-item[data-canton="'+selectedCanton+'"]';
}
if (showTypeOne){
if (showTypeTwo){
selector = cantonSelector;
//selector = cantonSelector+'[data-type="one"],'+cantonSelector+'[data-type="two"]';
}
else {
selector = cantonSelector+'[data-type="one"]';
}
}
else if (showTypeTwo){
selector = cantonSelector+'[data-type="two"]';
}
$('.list-item').hide();
console.log(selector);
$(selector).show();
}
$(document).ready(function($){
$(".filter-select").change(function() {
var selectedCanton = $("#canton").val();
var showTypeOne = $("#type-one").prop('checked');
var showTypeTwo = $("#type-two").prop('checked');
showItems(selectedCanton,showTypeOne,showTypeTwo);
});
});
you can use filter function of jquery.
try something like
$('.list-item').hide();
$('.list-item').filter(function (index, e) {
var condition = true;
var el = $(e);
if(showTypeOne)
{
condition = condition && (el.data("type") === "one");
}
if(showTypeTwo)
{
condition = condition && (el.data("type") === "two");
}
if(selectedCanton!='all')
{
condition = condition && (el.data("canton") === selectedCanton);
}
return condition;
})
.show();
you could add text filter easly that way..
working sample : http://jsfiddle.net/CufMp/1/
I am facing an issue with the numbered list in ckeditor. When I try to bold some text in li, only the text is getting bold, without the preceding number. This is how it looks like,
One
Two
Three
It should be like this
2. Two
When I check the source, I found the code like below
<li><strong>Two</strong></li>
I would like to know is there any way to change the working of bold button, so that it will add something like below
<li style="font-weight:bold">Two</li>
<p> Hello <strong>World</strong></p>
I tried to solve your problem.
My solution isn't the best, because I guess that create a bold plugin, that takes care about list items would be the best solution.
I make it without using jQuery; however, using it the code should became simpler and more readable.
First of all, we need to define something useful for the main task:
String trim. See this.
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
String contains. See this
String.prototype.contains = function(it) {
return this.indexOf(it) != -1;
};
First child element. The following function obtains the first child element, or not-empty text node, of the element passed as argument
function getFirstChildNotEmpty(el) {
var firstChild = el.firstChild;
while(firstChild) {
if(firstChild.nodeType == 3 && firstChild.nodeValue && firstChild.nodeValue.trim() != '') {
return firstChild;
} else if (firstChild.nodeType == 1) {
return firstChild;
}
firstChild = firstChild.nextSibling;
}
return firstChild;
}
Now, we can define the main two functions we need:
function removeBoldIfPresent(el) {
el = el.$;
var elStyle = el.getAttribute("style");
elStyle = (elStyle) ? elStyle : '';
if(elStyle.trim() != '' && elStyle.contains("font-weight:bold")) {
el.setAttribute("style", elStyle.replace("font-weight:bold", ''));
}
}
CKEDITOR.instances.yourinstance.on("change", function(ev) {
var liEls = ev.editor.document.find("ol li");
for(var i=0; i<liEls.count(); ++i) {
var el = liEls.getItem(i);
var nativeEl = el.$.cloneNode(true);
nativeEl.normalize();
var firstChild = getFirstChildNotEmpty(nativeEl);
if(firstChild.nodeType != 1) {
removeBoldIfPresent(el);
continue;
}
var firstChildTagName = firstChild.tagName.toLowerCase()
if(firstChildTagName == 'b' || firstChildTagName == 'strong') {
//TODO: you also need to consider the case in which the bold is done using the style property
//My suggest is to use jQuery; you can follow this question: https://stackoverflow.com/questions/10877903/check-if-text-in-cell-is-bold
var textOfFirstChild = (new CKEDITOR.dom.element(firstChild)).getText().trim();
var textOfLi = el.getText().trim();
if(textOfFirstChild == textOfLi) {
//Need to make bold
var elStyle = el.getAttribute("style");
elStyle = (elStyle) ? elStyle : '';
if(elStyle.trim() == '' || !elStyle.contains("font-weight:bold")) {
el.setAttribute("style", elStyle + ";font-weight:bold;");
}
} else {
removeBoldIfPresent(el);
}
} else {
removeBoldIfPresent(el);
}
}
});
You need to use the last release of CkEditor (version 4.3), and the onchange plugin (that is included by default in the full package).
CKEditor 4.1 remove your classes, styles, and attributes that is not specified in its rules.
If that's the problem, you might want to disable it by adding this line:
CKEDITOR.config.allowedContent = true;
Here is full code to use it:
window.onload = function() {
CKEDITOR.replace( 'txt_description' );
CKEDITOR.config.allowedContent = true; //please add this line after your CKEditor initialized
};
Please check it out here
<ul class="test">
<li><span>hello</span></li>
</ul>
.test li
{
font-weight:bold;
}
.test li span
{
font-weight:normal;
}
I am currently attempting to set up a set of chained selects using the Flexbox Jquery plugin (this is not specifically designed for chaining, but can be used for that).
I have the chaining working if I set everything explicitly, but I am trying to dry my code up and make it more understandable. As such, I have come up with the code below.
All boxes currently load initially, and make their queries. The problem I am having is that when I iterate through the menus (as below), I lose the onSelect functionality - it only fires for the last menu I loaded.
My understanding was that since I am using a different JQuery selector each time - $('#' + fbMenu.divId) - it would not matter that I then set the onSelect behavior for another menu, but evidently this is not the case. Am I somehow overwriting the binding each time I am loading a box?
Hopefully I don't have to specify the onSelect functionality for each dropdown, as there could be a large number of them.
Many thanks for any assistance you can provide!
$(document).ready(function() {
// Create the variables for data objects
var vehicleMakeFb = new Object();
var vehicleModelFb = new Object();
var vehicleTrimFb = new Object();
// Set up each menu with the divId, jsonUrl and the chlid menus that will be updated on select
vehicleMakeFb.divId = 'vehicle_vehicleMake_input';
vehicleMakeFb.jsonUrl = '/vehicles/getmakes';
vehicleMakeFb.children = [vehicleModelFb];
vehicleModelFb.divId = 'vehicle_vehicleModel_input';
vehicleModelFb.jsonUrl = '/vehicles/getmodels';
vehicleModelFb.children = [vehicleTrimFb];
vehicleTrimFb.divId = 'vehicle_vehicleTrim_input';
vehicleTrimFb.jsonUrl = '/vehicles/gettrims';
vehicleTrimFb.children = [];
// Create an array of all menu objects so that they can be iterated through
var allMenus = [vehicleMakeFb,vehicleModelFb,vehicleTrimFb];
// Create the parent menu
for (var i = 0; i < allMenus.length; i++) {
var fbMenu = allMenus[i];
alert(fbMenu.divId);
$('#' + fbMenu.divId).flexbox(fbMenu.jsonUrl + '.json', {
// Update the child menu(s), based on the selection of the first menu
onSelect: function() {
for (var i = 0; i < fbMenu.children.length; i++) {
var fbChild = fbMenu.children[i];
var hiddendiv = document.getElementById(fbMenu.divId + '_hidden');
var jsonurl1 = fbChild.jsonUrl + '/' + hiddendiv.getAttribute('value') + '.json';
alert(jsonurl1);
$('#' + fbChild.divId).flexbox(jsonurl1);
}
}
});
}
});
If you put all the information on the elements them selves i think you will have better results. Although I've been known to be wrong, I think the context of the select functions are getting mixed up.
instead of setting up each menu as an object try:
$(document).ready(function() {
var setupdiv = (function(divId, jsonUrl, children)
{
jQuery('#' + divId)
.data("jsonurl", jsonUrl)
.data("children", children.join(",#"));
// Create the parent menu
jQuery('#' + divId).flexbox(jsonUrl + '.json',
{
// Update the child menu(s), based on the selection of the first menu
onSelect: function()
{
var children = jQuery(this).data("children");
var jsonUrl = jQuery(this).data("jsonurl");
if(children)
{
children = jQuery('#' + children);
alert('children was true');
}
else
{
children = jQuery();
alert('children was false');
}
var hiddendiv = jQuery('#' + this.id + '_hidden');
children.each(function()
{
var childJsonUrl = jsonUrl + '/' + hiddendiv.val() + '.json';
alert(childJsonUrl);
$(this).flexbox(childJsonUrl);
});
}
});
});
setupdiv('vehicle_vehicleMake_input', '/vehicles/getmakes', ['vehicle_vehicleModel_input']);
setupdiv('vehicle_vehicleModel_input', '/vehicles/getmodels', ['vehicle_vehicleTrim_input']);
setupdiv('vehicle_vehicleTrim_input', '/vehicles/gettrims', []);
});
DISCLAIMER
I'm known for my spelling mistakes. Please spellcheck before using this code ;)
Update
I've changed the first two lines of code and I've normalized the indenting as there were a mix of tabs and spaces. Should be easier to read now.