select list doesn't retain selected value - javascript

I created custom <select> styles using jQuery for multiple select boxes in a form. But the <select> boxes don't show if any value pre-selected but always show "Please Select".
$('.custom_select').each(function() {
var list = $(this).children('ul'),
select = $(this).find('select'),
title = $(this).find('.select_title');
title.css('min-width', title.outerWidth());
// select items to list items
if ($(this).find('[data-filter]').length) {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li data-filter="' + select.children('option').eq(i).data('filter') + '" class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
} else {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
}
select.hide();
// open list
title.on('click', function() {
list.slideToggle(400);
$(this).toggleClass('active');
});
// selected option
list.on('click', 'li', function() {
var val = $(this).text();
title.text(val);
list.slideUp(400);
select.val(val);
title.toggleClass('active');
});
});
.select_title {
cursor: pointer;
padding: 2px 39px 3px 9px;
border: 2px solid #e4e4e2;
background: #f5f7f8;
z-index: 1;
min-width: 75px;
-webkit-transition: border-color .4s ease;
-moz-transition: border-color .4s ease;
-o-transition: border-color .4s ease;
transition: border-color .4s ease;
}
.select_list {
cursor: pointer;
width: 100%;
border-left: 2px solid #e4e4e2;
border-right: 2px solid #e4e4e2;
border-bottom: 2px solid #e4e4e2;
-webkit-border-bottom-left-radius: 4px;
-moz-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-moz-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
ul {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="custom_select relative">
<div class="select_title">Please Select</div>
<ul class="select_list d_none" style="display:none;"></ul>
<select name="title" id="title" required style="display:none;">
<option value=""></option>
<option value="Mr." selected="selected">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss</option>
</select>
</div>
How can I get to show if values selected?

I'd simply fetch the initial select value val() and assign it as text to the title container:
title.text(select.val() || 'Please Select');
If the selected value is empty (or no option is selected initialy), it will update title with a standard 'Please Select' text.
JSFiddle
If you want to have more controll over the code you can write the above code widely:
if(select.val()){
title.text(select.val());
// anything else ...
}else{
title.text('Please Select');
// anything else ...
}

Add below js code in your js and check
var text = $('#title').val();
if(text != ""){
$('.select_list li').each(function(){
if(text == $(this).text())
$(this).click();
});
}
$('.custom_select').each(function() {
var list = $(this).children('ul'),
select = $(this).find('select'),
title = $(this).find('.select_title');
title.css('min-width', title.outerWidth());
// select items to list items
if ($(this).find('[data-filter]').length) {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li data-filter="' + select.children('option').eq(i).data('filter') + '" class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
} else {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
}
select.hide();
// open list
title.on('click', function() {
list.slideToggle(400);
$(this).toggleClass('active');
});
// selected option
list.on('click', 'li', function() {
var val = $(this).text();
title.text(val);
list.slideUp(400);
select.val(val);
title.toggleClass('active');
});
});
var text = $('#title').val();
if(text != ""){
$('.select_list li').each(function(){
if(text == $(this).text())
$(this).click();
});
}
.select_title {
cursor: pointer;
padding: 2px 39px 3px 9px;
border: 2px solid #e4e4e2;
background: #f5f7f8;
z-index: 1;
min-width: 75px;
-webkit-transition: border-color .4s ease;
-moz-transition: border-color .4s ease;
-o-transition: border-color .4s ease;
transition: border-color .4s ease;
}
.select_list {
cursor: pointer;
width: 100%;
border-left: 2px solid #e4e4e2;
border-right: 2px solid #e4e4e2;
border-bottom: 2px solid #e4e4e2;
-webkit-border-bottom-left-radius: 4px;
-moz-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-moz-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
ul {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="custom_select relative">
<div class="select_title">Please Select</div>
<ul class="select_list d_none" style="display:none;"></ul>
<select name="title" id="title" required style="display:none;">
<option value=""></option>
<option value="Mr." selected="selected">Mr.</option>
<option value="Mrs." >Mrs.</option>
<option value="Miss.">Miss</option>
</select>
</div>

Related

By first click select div and unselect others, by second click on the same div unselect it

I would like to have the following scenario:
only one div can be selected at the time (DONE)
by click on the div it should be selected and other divs should stay unselected (DONE)
by click on the already selected div, that div should be unselected and other divs will stay also unselected(TO DO)
I'm having problem to implement the last feature where by click on the already selected div to unselect it and other already working features should work as before. Could someone help me to make it work ?
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
var selectedEl = document.querySelector(".selected");
if (selectedEl) {
selectedEl.classList.remove("selected");
}
this.classList.add("selected");
}, false);
}
.optionsecoptions {
width: 400px;
padding-left: 10px;
height: 40px;
background: #bbb8b8;
float: left;
font-size: 20px;
cursor: pointer;
}
.optionsecoptions:hover,
.optionsecoptions:active {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
.selected {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
<div style="margin-top:10px;">
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>
</div>
JSFiddle
You can do it like this:
// If there was a selected element which is not this
if (selectedEl && selectedEl !== this) {
selectedEl.classList.remove("selected");
}
// Toggle this
this.classList.toggle("selected");
As noted in the comments, your styles are a little misleading. You may want to have different styles on :hover and .selected. The demo below also changes that.
Demo:
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
var selectedEl = document.querySelector(".selected");
// If there was a selected element which is not this
if (selectedEl && selectedEl !== this) {
selectedEl.classList.remove("selected");
}
// Toggle this
this.classList.toggle("selected");
}, false);
}
.optionsecoptions {
width: 400px;
padding-left: 10px;
line-height: 40px;
background: #eceded;
font-size: 16px;
cursor: pointer;
font-family: Arial, Helvetica, sans-serif;
transition: background-color 0.1s ease-in;
}
.optionsecoptions:hover { background-color: #bfe5ff; }
.optionsecoptions:active { background-color: #2d546f; color: #ffffff; }
.selected { background-color: #226fa3; color: #ffffff; }
.selected:hover { background-color: #4d99cc; }
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>

Using jquery and css how do I create a delayed background color change animation?

I have a javascript-powered searchable html list. When the user types in some text that hones the list down to one result, I want the ".opaqueblock" div background to turn into a brighter color and then turn back to the original color after a quick delay. At the moment the color changes smoothly to a brighter when the user types in "Text 53" in the search box, but I can't figure out how to change the color back to the original darker color. I want a bright flash effect. Also, the each() function that I try to use to only change the background color of the isolated item "Text 53" is changing the background color of all the items. I do not want the color to change for list items that are hidden. Does anyone know a solution?
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.0.min.js""></script>
<script type="text/javascript" src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet'> <!--for search text-->
<link href='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet'> <!--for search text-->
<script>
function ListSearch() {
var input, filter, ul, li, a, i, txtValue, resultsCount = 0, resultText = " results"; // Declare variables
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("DocumentList");
li = ul.getElementsByTagName('li');
$('.opaqueBlock').css('border-color','transparent') //remove all borders in case a border was added when the results were honed down to 1
for (i = 0; i < li.length; i++) { // Loop through all list items, hide those that don't match query
a = li[i].getElementsByTagName("div")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
resultsCount++;
} else {
li[i].style.display = "none";
}
}
if (resultsCount == 1) {
$('.opaqueBlock').css('border-color','#68e8d5');
$('.PreviewArrow').css("opacity", "1"); document.getElementById("results_span").style.color = "#b6fbd2";
resultText = " result";
$(".opaqueBlock:visible").each(
$('.opaqueBlock').delay(300).css("background-color", "rgba(147,185,212,0.6)")
/* $('.opaqueBlock').delay(300).css("background-color", "rgba(72,97,115,0.6)"); */
);
}
else if(resultsCount < 1){document.getElementById("results_span").style.color = "#fbb6bc";}
else if(resultsCount < 3){document.getElementById("results_span").style.color = "#b6fbd2";}
else if(resultsCount < 4){document.getElementById("results_span").style.color = "#b6d7fb";}
else if(resultsCount < 5){document.getElementById("results_span").style.color = "#eeb8ff";}
else {document.getElementById("results_span").style.color = "#fbb6bc";}
document.getElementById("results_span").innerHTML = resultsCount + resultText;
}
$(document).ready(function(){
function HoverOverItem(thisParticularItem, DocImageLink){
if (!thisParticularItem.hasClass("active_form_item") ) {
$(".PreviewContainer").css("opacity", "0.3");
$(".PreviewContainer").css("background-image", DocImageLink);
$(".PreviewContainer").animate({'opacity': '1'},500);
$("#ContentContainer").find('.active_form_item').removeClass('active_form_item');
thisParticularItem.addClass("active_form_item");
}
}
});
$(window).load(function(){
$("#myInput").focus();
var ul, li, resultsCount = 0, resultText = " searchable documents"; // Declare variables
ul = document.getElementById("DocumentList");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {resultsCount++;} // Loop through all list items to get a count
document.getElementById("results_span").innerHTML = resultsCount + resultText;
});
</script>
<style>
#ContentContainer{
height: 700px;
background-color: #132e54;
}
#ContentContainer a{text-decoration: none;}
#ContentContainer img{border: none;}
#search_prompt_div{margin-left: 16px;}
#search_prompt_div p{color: white; font-size: 14px; margin-bottom: 12px; font-family: comfortaa;}
#search_prompt_div input{height: 25px;font-size: 16px; width: 300px; font-family: comfortaa;}
#search_prompt_div #results_span{display: inline-block;margin-left: 6px; color: #fbb6bc; font-size: 12px;}
#DocumentListContainer{
height: 600px;
width: 660px;
overflow: hidden;
}
#DocumentList{
list-style-type: none;
margin: 0;
padding: 6px 0 0 0;
width: 105%;
overflow: auto;
height: 893px;
}
.opaqueBlock{
opacity: 1; /*can set this to 0 if you want to animate it*/
margin-left: 56px; /*can set this to 0 if you want to animate it*/
display: inline-block;
width: 490px;
height: 35px;
border: 2px solid transparent;
background-color: rgba(72,97,115,0.6);
border-radius: 10px;
-webkit-transition: all .6s ease;
-moz-transition: all .6s ease;
-ms-transition: all .6s ease;
-o-transition: all .6s ease;
}
.opaqueBlock:hover{
border: 2px solid #5cb1d8;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";
opacity:0.7 !important;
}
.fileLinkContainer{
width: 630px;
height: 37px;
margin-bottom: 10px;
position: relative;
}
.fileTextSpan{
margin-left: 10px;
color: white;
margin-top: 5px;
font-family: 'Nunito' !important;
font-size: 19px !important;
display: inline-block;
}
</style>
<div id="ContentContainer">
<br><br><br>
<div id="search_prompt_div">
<p>Type something in the search box to find what you are looking for:</p>
<input id="myInput" type="text" placeholder="Search..." onkeyup="ListSearch()">
<span id="results_span"></span>
</div>
<br/><br/><br/>
<div class="PreviewContainer"></div>
<div id="DocumentListContainer">
<ul id="DocumentList">
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 1</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 11</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 21</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 33</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 53</span></div></div></li>
</ul>
</div>
</div>
What about to use CSS keyframes somehow like this?
#keyframes anim {
0% { background-color: #fff; }
50%, 70% { background-color: #333; }
100% { background-color: #fff; }
}
Then just toggle class on the element by JS

Checking to see if a select input is filled in and then showing another input

As you will be able to see in the snippet, once an input is filled out, another is shown, if it has a length of more than 3 characters. The issue I am running into is getting the same concept to work for select inputs. I added the following outside of the if($.trim(this.value).length > 3) { because the value would never be over 3 characters.
if($('#has-color').val()){
$nextLabel.has(":input").addClass("show");
} else {
// do something else
}
However, I cannot get the next select box to show. I am not sure if it is not detecting what the value of the select box is and passing it through or if I am just not doing it right.
I have also tried $nextLabel.has(":select").addClass("show"); with the same, non-working results.
Any ideas what I am doing wrong?
$(".labelsGroup").each(function() {
var $thatGroup = $(this);
var $nextGroup = $thatGroup.next(".labelsGroup");
var $inputs = $thatGroup.find("input");
var $selects = $thatGroup.find("select");
var $proceed = $thatGroup.find("button");
$inputs.on("input", function(){
var $nextLabel = $(this).closest("label").next("label");
if($.trim(this.value).length > 3) {
$nextLabel.has(":input").addClass("show");
}
if($('#has-color').val()){
$nextLabel.has(":input").addClass("show");
} else {
// do something else
}
});
$proceed.on("click", function(e){
$("html, body").animate({ scrollTop: 0 }, 200);
e.preventDefault();
var allValid = $inputs.filter(function() {
return $.trim(this.value).length > 3;
}).length === $inputs.length;
// TODO: use a better validation plugin than the above
if(allValid) { // Finally proceed!!
$thatGroup.addClass("hide");
$nextGroup.addClass("show");
// TODO: Submit form using AJAX to a service
} else { // or Log error!!
return alert("Please fill-in the missing fields!");
}
});
});
.labelsGroup {
text-align: center;
}
.labelsGroup label {
display: block;
margin: 50px 0;
font-size: 1.4em;
}
.labelsGroup label input, .labelsGroup label select {
background: #fff;
padding: 15px 15px;
border: 1px solid #999;
width: 40%;
font-size: 1.3em !important;
}
.labelsGroup input, .labelsGroup select {
margin-top: 20px;
}
.proceed-button {
background: #0085A1;
color: #FFF;
padding: 15px 20px;
border: none;
font-size: 1.2em;
margin-top: 15px;
cursor: pointer;
webkit-transition: .7s ease;
transition: .7s ease;
display: inline-block;
width: auto;
}
.proceed-button:hover {
background: #005b6e;
webkit-transition: .7s ease;
transition: .7s ease;
}
/* hide all but first label in parent */
/* hide all subsequent labelsParents */
.labelsGroup label + label,
.labelsGroup + .labelsGroup,
.hide {
opacity: 0;
visibility: hidden;
position: absolute;
}
.show {
opacity: 1 !important;
visibility: visible !important;
position: relative !important;
-webkit-transition: opacity 0.7s ease-in;
transition: opacity 0.7s ease-in;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="labelsGroup">
<div class="container-intro">First, let's find out a little bit about you.</div>
<label>
What is your name?<br>
<input name="name" type="text"><!-- PS: use name="" instead of id=""-->
</label>
<label>
Email address<br>
<input name="email" type="email">
</label>
<label>
<button class="proceed-button">PROCEED</button>
</label>
</div>
<div class="labelsGroup">
<div class="container-intro">Now let's go over existing information.</div>
<label>
Do you have a favorite color?<br>
<select name="color-question" id="has-color">
<option value="" disabled selected>Please choose option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
<label>
What is it?<br>
<select name="answered-question" id="has-answered">
<option value="" disabled selected>Please choose option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
<label>
<button class="proceed-button">PROCEED</button>
</label>
</div>
What if you do something like this:
$('#has-color').on("change", function(){
var $nextLabel = $(this).closest("label").next("label");
if($('#has-color').val()){
$nextLabel.has(":input").addClass("show");
} else {
$nextLabel.has(":input").removeClass("show");
}
});
for all your selects?

CSS Checkbox style to toggle a value

I am currently writing a program which toggles a value based on the status of a checkbox. With a normal checkbox everything works fine.
HTML:
<td><script> checkbox('px_THPressure_Enable')</script></td>
<td><script> checkbox('px_THPressure_Activate')</script></td>
Javascript checkbox function:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<input type='checkbox' class='fetch' onClick=\""+onClicked+"\" id='" + register + "'>";
document.write(output);
}
Now I am trying to style the checkbox with CSS as described here http://www.paulund.co.uk/style-checkboxes-with-css "Checkbox Four"
So now my checkbox function changed to:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<div class='checkboxFour'><input type='checkbox' class='fetch' value='1' onClick=\""+onClicked+"\" id='" + register + "' name=''></input><label for='checkboxFourInput'></label></div>";
document.write(output);
}
CSS:
input[type=checkbox] {
visibility: hidden;
}
/**
* Checkbox Four
*/
.checkboxFour {
width: 40px;
height: 40px;
background: #ddd;
margin: 20px 90px;
border-radius: 100%;
position: relative;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checkbox button
*/
.checkboxFour label {
display: block;
width: 30px;
height: 30px;
border-radius: 100px;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
-o-transition: all .5s ease;
-ms-transition: all .5s ease;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 5px;
left: 5px;
z-index: 1;
background: #333;
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checked state
*/
.checkboxFour input[type=checkbox]:checked + label {
background: #26ca28;
}
Now I am able to see the correct status of the checkbox with the new style but when I click the checkbox the value does not change. I know that the issue is in the id field. The checkbox style requires the id="checkboxFourInput" and my program requires the id to equal the register value which is being toggled. ie THPressure_Enable
I know that having multiple ids on an html element is not allowed, so is there any way that I can toggle this register value with the styled checkbox.
Thank you in advance.
EDIT:
It is a function that will change the register value depending on the correct authorization. I have the function defined as follows:
function setDataJQuery(register,value)
{
statusElem = document.getElementById('status');
if (statusElem)
statusElem.innerHTML=" ";
//alert("logged in as " + "<?php echo \"{$_SERVER['PHP_AUTH_USER']}\"; ?>");
if (((user_name == 'slipsmart' || user_name== 'slipsmart_super') && (operator_set_ok.indexOf(register.substring(3)) != -1)) ||
(user_name == 'slipsmart_super' && (supervisor_set_ok.indexOf(register.substring(3)) != -1)) ||
user_name == 'slipsmart_setup')
{
$.ajax({
url: 'set.php?' + register + '=' + value,
type: 'post',
success:function(data){
var val_pairs = data.split("&");
document.getElementById('Error').innerHTML=" ";
for (i in val_pairs)
{
var pair = val_pairs[i].split("=");
var myElem = document.getElementById(pair[0]);
if (myElem)
myElem.innerHTML= pair[1];
}
}
});
}
else
alert("Not authorized!");
}

How can I use <ul> list instead of <select> dropdown for the languages switcher?

I use msDropDown to convert the <select> to <ul> list for languages switcher. But the problem is that with this jQuery plugin, the select takes a long time to load after page loaded.
So, how can I use a ul list rather than select?
This is my select code:
<select name="lang" class="language" onchange="location.href='index.php?lang='+this.value+''.$trackpage.'">
<option name="lang" data-image="style/lang/de.png" value="de">Deutsch</option>
<option name="lang" data-image="style/lang/en.png" value="en" selected="selected">English</option>
<option name="lang" data-image="style/lang/es.png" value="es">Espanol</option>
<option name="lang" data-image="style/lang/fr.png" value="fr">Francais</option>
<option name="lang" data-image="style/lang/it.png" value="it">Italiano</option>
</select>
I tried with:
<ul onchange="location.href='index.php?lang='+this.value+'">
<li>
English
</li>
</ul>
but value and onchange is not supported by ul and a.
Is there a way to make ul works with the select attributes?
Thank you! And sorry for my bad English!
Updated Answer 2015
As this question is still visited very often and due to some requests in the comments, I've revisit my code. You can still find my original answer below.
HTML
<button class="language_selector">Choose Language</button>
<ul class="languages">
<li>English</li>
<li>Deutsch</li>
</ul>
<article>
<h1>More Content</h1>
</article>
JavaScript
var trigger = $('.language_selector');
var list = $('.languages');
trigger.click(function() {
trigger.toggleClass('active');
list.slideToggle(200);
});
// this is optional to close the list while the new page is loading
list.click(function() {
trigger.click();
});
CSS
.language_selector {
width: 200px;
background: #222;
color: #eee;
line-height: 25px;
font-size: 14px;
padding: 0 10px;
cursor: pointer;
}
.languages {
display: none;
position: absolute;
margin: 0;
background: #dddddd;
}
.languages > li {
width: 200px;
background: #eee;
line-height: 25px;
font-size: 14px;
padding: 0 10px;
cursor: pointer;
}
.languages > li:hover {
background: #aaa;
}
Demo
Try before buy
Original Answer From 2013
I would do it like this:
var nav = $('#nav');
var selection = $('.select');
var select = selection.find('li');
nav.click(function(event) {
if (nav.hasClass('active')) {
nav.removeClass('active');
selection.stop().slideUp(200);
} else {
nav.addClass('active');
selection.stop().slideDown(200);
}
event.preventDefault();
});
select.click(function(event) {
// updated code to select the current language
select.removeClass('active');
$(this).addClass('active');
alert ("location.href = 'index.php?lang=" + $(this).attr('data-value'));
});
h2 {
width: 200px;
background: #222;
color: #eee;
line-height: 25px;
font-size: 14px;
padding: 0 10px;
cursor: pointer;
}
ol.select {
display: none;
}
ol.select > li {
width: 200px;
background: #eee;
line-height: 25px;
font-size: 14px;
padding: 0 10px;
cursor: pointer;
}
ol.select > li:hover {
background: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h2 id="nav">Choose Language</h2>
<ol class="select">
<li data-value="en">English</li>
<li data-value="de">Deutsch</li>
</ol>
This one adds a class the the selected element. This works, if you stay on that very page after the select and don't use location.href.
You can't use the select attributes, instead you can create your own attributes and use them in <ul> element
Maybe this will help you
First the html code
<div id="language">Change Lang</div>
<ul id="lang">
<li>
<a href="" name="lang" data-val="de">
<img src="http://icons.iconarchive.com/icons/famfamfam/flag/16/ad-icon.png"/>
English</a></li>
<li>
<a href="" name="lang" data-val="he">
<img src="http://icons.iconarchive.com/icons/famfamfam/flag/16/il-icon.png"/>
Hebrew</a></li>
</ul>
Next the jquery code
$("#language").click(function(){
$("#lang li").slideToggle();
});
$("#lang li").click(function() {
var url = location.href = "index.php?lang=" + $(this).find('a').attr("data-val");
location.href =url;
});
i have did it without the plugin.
Pay attention that i created a data-val attribute so store the desire language.
and i getting this attribute using jquery code
A very simple one (ul to select dropdown jquery transformation) no need to change html, very useful for mobile menus:
$(function(){
var close = function() {
$("ul").each(function() {
var $thisUl = $(this);
if($thisUl.find("li > a.click").length == 0) {
var $li = $(document.createElement('li')).append($(document.createElement('a')).attr({
"class": "click selectable visible",
"href": "#"
}).text("Select"));
$thisUl.append($li);
}
else {
$thisUl.find("li > a.click").addClass("visible");
}
$thisUl.find("li:has(> a:not(.click))").hide();
$thisUl.find("li > a.click").show();
});
};
var sentinel = function() {
$("ul").each(function(){
var $thisUl = $(this);
$($thisUl).find("li > a").click(function(event){
if($(event.target).is('ul li a.visible')) {
event.preventDefault();
$thisUl.find("li:has(> a:not(.click))").show();
$thisUl.find("li > a.selectable").hide();
$thisUl.find("li > a.click").removeClass("visible");
}
else {
$thisUl.find("li").each(function(){
$(this).find("a").removeClass("click selectable visible");
$(this).find("a.selectable").remove();
});
$(this).addClass("click visible");
close();
}
});
});
};
var reconnaissance = function() {
$(document).click(function(event) {
if(!$(event.target).is('ul li a')) {
close();
}
});
};
close();
sentinel();
reconnaissance();
});
ul {
width: auto;
margin: 2px auto;
background-color: #ddd;
border-top: 1px solid #999;
border-bottom: 3px solid #999;
border-left: 1px solid #999;
border-right: 1px solid #999;
border-radius: 8px;
list-style:none;
background-size: 16px 16px;
background-repeat: no-repeat;
background-attachment: scroll;
background-position: left 2px;
background-color: transparent;
cursor: pointer;
}
li > a.click {
color: darkgreen;
font-weight: bold;
}
li a {
color:darkblue;
text-decoration:none;
}
li a:active, li a:hover {
color:darkred;
background-color: lightyellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>Option 1</li>
<li><a class="click" href="#">Option 2</a></li>
<li>Option 3</li>
</ul>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
// Generated by CoffeeScript 1.4.0
(function() {
var $;
$ = window.jQuery || window.Zepto || window.$;
$.fn.fancySelect = function(opts) {
var isiOS, settings;
if (opts == null) {
opts = {};
}
settings = $.extend({
forceiOS: false,
includeBlank: false,
optionTemplate: function(optionEl) {
return optionEl.text();
},
triggerTemplate: function(optionEl) {
return optionEl.text();
}
}, opts);
isiOS = !!navigator.userAgent.match(/iP(hone|od|ad)/i);
return this.each(function() {
var copyOptionsToList, disabled, options, sel, trigger, updateTriggerText, wrapper;
sel = $(this);
if (sel.hasClass('fancified') || sel[0].tagName !== 'SELECT') {
return;
}
sel.addClass('fancified');
sel.css({
width: 1,
height: 1,
display: 'block',
position: 'absolute',
top: 0,
left: 0,
opacity: 0
});
sel.wrap('<div class="fancy-select">');
wrapper = sel.parent();
if (sel.data('class')) {
wrapper.addClass(sel.data('class'));
}
wrapper.append('<div class="trigger">');
if (!(isiOS && !settings.forceiOS)) {
wrapper.append('<ul class="options">');
}
trigger = wrapper.find('.trigger');
options = wrapper.find('.options');
disabled = sel.prop('disabled');
if (disabled) {
wrapper.addClass('disabled');
}
updateTriggerText = function() {
var triggerHtml;
triggerHtml = settings.triggerTemplate(sel.find(':selected'));
return trigger.html(triggerHtml);
};
sel.on('blur.fs', function() {
if (trigger.hasClass('open')) {
return setTimeout(function() {
return trigger.trigger('close.fs');
}, 120);
}
});
trigger.on('close.fs', function() {
trigger.removeClass('open');
return options.removeClass('open');
});
trigger.on('click.fs', function() {
var offParent, parent;
if (!disabled) {
trigger.toggleClass('open');
if (isiOS && !settings.forceiOS) {
if (trigger.hasClass('open')) {
return sel.focus();
}
} else {
if (trigger.hasClass('open')) {
parent = trigger.parent();
offParent = parent.offsetParent();
if ((parent.offset().top + parent.outerHeight() + options.outerHeight() + 20) > $(window).height() + $(window).scrollTop()) {
options.addClass('overflowing');
} else {
options.removeClass('overflowing');
}
}
options.toggleClass('open');
if (!isiOS) {
return sel.focus();
}
}
}
});
sel.on('enable', function() {
sel.prop('disabled', false);
wrapper.removeClass('disabled');
disabled = false;
return copyOptionsToList();
});
sel.on('disable', function() {
sel.prop('disabled', true);
wrapper.addClass('disabled');
return disabled = true;
});
sel.on('change.fs', function(e) {
if (e.originalEvent && e.originalEvent.isTrusted) {
return e.stopPropagation();
} else {
return updateTriggerText();
}
});
sel.on('keydown', function(e) {
var hovered, newHovered, w;
w = e.which;
hovered = options.find('.hover');
hovered.removeClass('hover');
if (!options.hasClass('open')) {
if (w === 13 || w === 32 || w === 38 || w === 40) {
e.preventDefault();
return trigger.trigger('click.fs');
}
} else {
if (w === 38) {
e.preventDefault();
if (hovered.length && hovered.index() > 0) {
hovered.prev().addClass('hover');
} else {
options.find('li:last-child').addClass('hover');
}
} else if (w === 40) {
e.preventDefault();
if (hovered.length && hovered.index() < options.find('li').length - 1) {
hovered.next().addClass('hover');
} else {
options.find('li:first-child').addClass('hover');
}
} else if (w === 27) {
e.preventDefault();
trigger.trigger('click.fs');
} else if (w === 13 || w === 32) {
e.preventDefault();
hovered.trigger('click.fs');
} else if (w === 9) {
if (trigger.hasClass('open')) {
trigger.trigger('close.fs');
}
}
newHovered = options.find('.hover');
if (newHovered.length) {
options.scrollTop(0);
return options.scrollTop(newHovered.position().top - 12);
}
}
});
options.on('click.fs', 'li', function(e) {
var clicked;
clicked = $(this);
sel.val(clicked.data('raw-value'));
if (!isiOS) {
sel.trigger('blur.fs').trigger('focus.fs');
}
options.find('.selected').removeClass('selected');
clicked.addClass('selected');
return sel.val(clicked.data('raw-value')).trigger('change.fs').trigger('blur.fs').trigger('focus.fs');
});
options.on('mouseenter.fs', 'li', function() {
var hovered, nowHovered;
nowHovered = $(this);
hovered = options.find('.hover');
hovered.removeClass('hover');
return nowHovered.addClass('hover');
});
options.on('mouseleave.fs', 'li', function() {
return options.find('.hover').removeClass('hover');
});
copyOptionsToList = function() {
var selOpts;
updateTriggerText();
if (isiOS && !settings.forceiOS) {
return;
}
selOpts = sel.find('option');
return sel.find('option').each(function(i, opt) {
var optHtml;
opt = $(opt);
if (!opt.prop('disabled') && (opt.val() || settings.includeBlank)) {
optHtml = settings.optionTemplate(opt);
if (opt.prop('selected')) {
return options.append("<li data-raw-value=\"" + (opt.val()) + "\" class=\"selected\">" + optHtml + "</li>");
} else {
return options.append("<li data-raw-value=\"" + (opt.val()) + "\">" + optHtml + "</li>");
}
}
});
};
sel.on('update.fs', function() {
wrapper.find('.options').empty();
return copyOptionsToList();
});
return copyOptionsToList();
});
};
}).call(this);
div.fancy-select {
position: relative;
color: #505050;
}
div.fancy-select.disabled {
opacity: 0.5;
}
div.fancy-select select:focus + div.trigger {
}
div.fancy-select select:focus + div.trigger.open {
}
div.fancy-select div.trigger {
cursor: pointer;
height: 50px;
line-height: 50px;
padding-left: 20px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
position: relative;
width: 100%;
border: 1px solid #6e6e6e;
transition: all 240ms ease-out;
-webkit-transition: all 240ms ease-out;
-moz-transition: all 240ms ease-out;
-ms-transition: all 240ms ease-out;
-o-transition: all 240ms ease-out;
}
div.fancy-select div.trigger:after {
content: "";
display: block;
position: absolute;
width: 0;
height: 0;
border: 5px solid transparent;
border-top-color: #4B5468;
top: 20px;
right: 9px;
}
div.fancy-select div.trigger.open {
}
div.fancy-select div.trigger.open:after {
}
div.fancy-select ul.options {
list-style: none;
margin: 0;
position: absolute;
top: 49px;
left: 0;
visibility: hidden;
opacity: 0;
z-index: 50;
max-height: 200px;
overflow: auto;
border: 1px solid #6e6e6e;
width: 100%;
padding: 0;
background: #fff;
transition: opacity 300ms ease-out, top 300ms ease-out, visibility 300ms ease-out;
-webkit-transition: opacity 300ms ease-out, top 300ms ease-out, visibility 300ms ease-out;
-moz-transition: opacity 300ms ease-out, top 300ms ease-out, visibility 300ms ease-out;
-ms-transition: opacity 300ms ease-out, top 300ms ease-out, visibility 300ms ease-out;
-o-transition: opacity 300ms ease-out, top 300ms ease-out, visibility 300ms ease-out;
}
div.fancy-select ul.options.open {
visibility: visible;
top: 50px;
opacity: 1;
/* have to use a non-visibility transition to prevent this iOS issue (bug?): */
/*http://stackoverflow.com/questions/10736478/css-animation-visibility-visible-works-on-chrome-and-safari-but-not-on-ios*/
transition: opacity 300ms ease-out, top 300ms ease-out;
-webkit-transition: opacity 300ms ease-out, top 300ms ease-out;
-moz-transition: opacity 300ms ease-out, top 300ms ease-out;
-ms-transition: opacity 300ms ease-out, top 300ms ease-out;
-o-transition: opacity 300ms ease-out, top 300ms ease-out;
}
div.fancy-select ul.options.overflowing {
top: auto;
bottom: 40px;
transition: opacity 300ms ease-out, bottom 300ms ease-out, visibility 300ms ease-out;
-webkit-transition: opacity 300ms ease-out, bottom 300ms ease-out, visibility 300ms ease-out;
-moz-transition: opacity 300ms ease-out, bottom 300ms ease-out, visibility 300ms ease-out;
-ms-transition: opacity 300ms ease-out, bottom 300ms ease-out, visibility 300ms ease-out;
-o-transition: opacity 300ms ease-out, bottom 300ms ease-out, visibility 300ms ease-out;
}
div.fancy-select ul.options.overflowing.open {
top: auto;
bottom: 50px;
transition: opacity 300ms ease-out, bottom 300ms ease-out;
-webkit-transition: opacity 300ms ease-out, bottom 300ms ease-out;
-moz-transition: opacity 300ms ease-out, bottom 300ms ease-out;
-ms-transition: opacity 300ms ease-out, bottom 300ms ease-out;
-o-transition: opacity 300ms ease-out, bottom 300ms ease-out;
}
div.fancy-select ul.options li {
padding: 8px 20px;
color: #000;
cursor: pointer;
white-space: nowrap;
transition: all 150ms ease-out;
-webkit-transition: all 150ms ease-out;
-moz-transition: all 150ms ease-out;
-ms-transition: all 150ms ease-out;
-o-transition: all 150ms ease-out;
}
div.fancy-select ul.options li.selected {
background: #d3d3d3;
color: #000;
}
div.fancy-select ul.options li:hover, div.fancy-select ul.options li.hover {
background: #d3d3d3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="SortBy" id="SortBy" class="filters-toolbar__input">
<option value="" selected="selected">Option 1</option>
<option value="" selected="selected">Option 2</option>
<option value="" selected="selected">Option 3</option>
</select>
/* --- fancySelect --- */
$(function() {
$('#SortBy').fancySelect();
});

Categories

Resources