Making ul li dropdown filter - javascript

I have a dropdown menu, now trying to use it as a filter. pass a value when I click the menu item start filtering But I am a bit confused at Jquery part. How to pass "name" & "value" and start filtering. And the important issue is when I click one item and filter. After that when I click next item, I don't want it to start over. I want to keep old history of search. and add it to new filter.
var allOptions = $(".init").children('li');
$("ul").on("click", function() {
allOptions.removeClass('selected');
$(this).addClass('selected');
$("ul").children('.init').html($(this).html());
allOptions.slideUp();
});
#filter-wrapper
{
margin-top:15px
}
#filter-wrapper ul
{
list-style:none;
position:relative;
float:left;
margin:0;
padding:0
}
#filter-wrapper ul a
{
display:block;
color:#333;
text-decoration:none;
font-weight:700;
font-size:12px;
line-height:32px;
padding:0 15px;
font-family:"HelveticaNeue","Helvetica Neue",Helvetica,Arial,sans-serif
}
#filter-wrapper ul li
{
position:relative;
float:left;
margin:0;
padding:0
}
#filter-wrapper ul li.current-menu-item
{
background:#ddd
}
#filter-wrapper ul li:hover
{
background:#f6f6f6
}
#filter-wrapper ul ul
{
display:none;
position:absolute;
top:100%;
left:0;
background:#fff;
padding:0
}
#filter-wrapper ul ul li
{
float:none;
width:200px
}
#filter-wrapper ul ul a
{
line-height:120%;
padding:10px 15px
}
#filter-wrapper ul ul ul
{
top:0;
left:100%
}
#filter-wrapper ul li:hover > ul
{
display:block
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="filter-wrapper">
<ul>
<li name="sortbyprice" class="current-menu-item">Cheapest Cars</li>
<li name="sortbyprice" class="current-menu-item">Newest Cars</li>
<li>Car Color
<ul class="init" name="sortbycolor">
<li data-value="red">Red</li>
<li data-value="black">Black</li>
<li data-value="silver">Silver</li>
</ul>
</li>
</ul>
</div>
For example, when I select Red then Car Color changed with the Red.
P.S: And by the way the name="" that I gave, it comes from Laravel controller. It contains the data.
And this is the old filter of mine. It's working with this. I can filter the data.
<form>
<select name="sortbyprice" class="custom-select custom-select-md" style="width: 100px;">
<option value="asc">cheapest</option>
<option value="desc">Expensive</option>
</select>
<select id="cars" name="cars" class="custom-select custom-select-md" style="width: 100px;">
<option value="" disabled selected>car colors</option>
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
</select>
<button type="submit" name="button" class="btn btn-success" id="filter-btn">Filter</button>
</form>

Not sure whether this is what you want, but you can try the code below and tell me what you think
var mockData = [
{
make: 'a',
color: 'red',
price: 1000
},
{
make: 'a',
color: 'black',
price: 2000
},
{
make: 'b',
color: 'red',
price: 1
},
{
make: 'a',
color: 'silver',
price: 3000
},
{
make: 'c',
color: 'black',
price: 1500
},
{
make: 'a',
color: 'red',
price: 1500
}
];
var allOptions = $('.init').children('li');
// use an object to store the filter options selected by the user
// you can then use the information in this object to do the filtering
// by sending an AJAX request or just filter the already fetched data
var filterOptions = {
sortbycolor: '',
sortbymake: '',
sortbyprice: ''
};
$(allOptions).on('click', function () {
// get the items' data-value
var value = $(this)[0].dataset.value;
// select the corresponding <a> tag
var button = $(this).parent()[0].previousElementSibling;
// get the corresponding name attribute, e.g. sortbycolor
var type = $($(this).parent()[0]).attr('name');
// set the filterOptions
filterOptions[type] = value;
// change the displayed text of the filter when the user select something
$(button).text(function (idx, content) {
// here I choose using a colon ':' as the separator,
// you can use whatever you want
var colonIndex = content.indexOf(':');
// example for baseContent is 'Car Color'
var baseContent = content;
if (colonIndex > -1) {
baseContent = content.slice(0, colonIndex);
}
// e.g 'Car Color: red
return baseContent + ': ' + value;
});
allOptions.slideUp();
console.log('update filterOptions: ', filterOptions);
// filter the already fetched data
var filteredData = mockData.filter(function (val) {
var isValid = true;
if (isValid && filterOptions.sortbycolor) {
isValid = val.color === filterOptions.sortbycolor;
}
if (isValid && filterOptions.sortbymake) {
isValid = val.make === filterOptions.sortbymake;
}
return isValid;
});
// sort the data by price
// hard-code the sorting direction here for simplicity,
// you can set this dynamically with the onclick event
filterOptions.sortbyprice = 'asc';
if (filterOptions.sortbyprice === 'asc') {
filteredData.sort(function (a, b) {
return a.price - b.price;
});
} else if (filterOptions.sortbyprice === 'desc') {
filteredData.sort(function (a, b) {
return b.price - a.price;
});
}
console.log('filteredData: ', filteredData);
// or you can send an ajax request to the server,
// and let the server handle the filtering for you
// you have to set the keys and values inside
// the 'data' youself, below is just an example
// as I don't know what your server's API looks like
$.get({
url: 'url-to-your-server',
data: {
color: filterOptions.sortbycolor,
make: filterOptions.sortbymake
},
success: function (response) {
// do something with the response,
// maybe it contains the filtered result
// however, I am not sure how does your API look like
}
});
});
// to deal with the left over css style(display: none) introduced by .slideUp()
$('.dropdown').on('mouseenter', function () {
allOptions.css('display', 'block');
});
console.log('initial filterOptions: ', filterOptions);
#filter-wrapper {
margin-top: 15px
}
#filter-wrapper ul {
list-style: none;
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul a {
display: block;
color: #333;
text-decoration: none;
font-weight: 700;
font-size: 12px;
line-height: 32px;
padding: 0 15px;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}
#filter-wrapper ul li {
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul li.current-menu-item {
background: #ddd
}
#filter-wrapper ul li:hover {
background: #f6f6f6
}
#filter-wrapper ul ul {
display: none;
position: absolute;
top: 100%;
left: 0;
background: #fff;
padding: 0
}
#filter-wrapper ul ul li {
float: none;
width: 200px
}
#filter-wrapper ul ul a {
line-height: 120%;
padding: 10px 15px
}
#filter-wrapper ul ul ul {
top: 0;
left: 100%
}
#filter-wrapper ul li:hover>ul {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filter-wrapper">
<ul>
<li name="sortbyprice" class="current-menu-item">Cheapest Cars</li>
<li name="sortbyprice" class="current-menu-item">Newest Cars</li>
<li class="dropdown">
Car Color
<ul class="init" name="sortbycolor">
<li data-value="red">Red</li>
<li data-value="black">Black</li>
<li data-value="silver">Silver</li>
</ul>
</li>
<li class="dropdown">
Make
<ul class="init" name="sortbymake">
<li data-value="a">A</li>
<li data-value="b">B</li>
<li data-value="c">C</li>
</ul>
</li>
</ul>
</div>

I eliminated your css, you are just interested in the color value - correct ?
<div id="filter-wrapper">
<ul>
<li name="sortbyprice" class="current-menu-item">Cheapest Cars</li>
<li name="sortbyprice" class="current-menu-item">Newest Cars</li>
<li>Car Color
<ul class="init" name="sortbycolor">
<li>Red</li>
<li>Black</li>
<li>Silver</li>
</ul>
</li>
</ul>
</div>
<script>
var allOptions = $(".init").children('li');
// I think you are only interested in the html content of the a (anchor)
$("li[data-value] > a").on("click", function(e) {
e.preventDefault();
allOptions.removeClass('selected');
$(this).addClass('selected');
let filterVal = $(this).data('value'); // do something with this ...
let li = $('<li />').html( filterVal);
$("ul.init").html('').append( li); // ul.init just has the value of the filter
// allOptions.slideUp(); // superfluos
});
</script>

Related

Dropdown menu save the choice on reload

I need to create popup language dropdown menu with country name, flag and link to the language version of the site. After user select menu item - it should take you to the needed url (language version of the page) and this choice should stay visible on the new page (after reload).
Example of the menu - https://prnt.sc/sjumj8 (https://www.farfetch.com/shopping/women/items.aspx)
Here is an example of what I'm trying to create: https://jsfiddle.net/Okean/8x0atLpy/62/
<ul class="list-unstyled" id="select-lang">
<li class="init">[SELECT]</li>
<li data-value="value 1"> <img src="https://image.flaticon.com/icons/svg/197/197615.svg"> Language 1 </li>
<li data-value="value 2"> <img src="https://image.flaticon.com/icons/svg/197/197386.svg">Language 2 </li>
<li data-value="value 3"> <img src="https://image.flaticon.com/icons/svg/197/197484.svg">Language 3 </li>
<li data-value="value 4"> <img src="https://image.flaticon.com/icons/svg/197/197380.svg">Language 4 </li>
</ul>
$("ul").on("click", ".init", function() {
$(this).closest("ul").children('li:not(.init)').toggle();
});
var allOptions = $("ul").children('li:not(.init)');
$("ul").on("click", "li:not(.init)", function() {
allOptions.removeClass('selected');
$(this).addClass('selected');
$("ul").children('.init').html($(this).html());
allOptions.toggle();
});
window.onload = function() {
var selItem = sessionStorage.getItem("SelItem");
$('#select-lang').val(selItem);
}
$('#select-lang').change(function() {
var selVal = $(this).val();
sessionStorage.setItem("SelItem", selVal);
});
body{
padding:30px;
}
ul {
height: 30px;
width: 150px;
border: 1px #000 solid;
}
ul li { padding: 5px 10px; z-index: 2; }
ul li:not(.init) { float: left; width: 130px; display: none; background: #ddd; }
ul li:not(.init):hover, ul li.selected:not(.init) { background: #09f; }
li.init { cursor: pointer; }
a#submit { z-index: 1; }
li img {
width: 20px;
}
You can use localStorage. Once user is selected an option, you can save it to browser's local storage where 'language' is your key and you can name it anything and where 'selectedOption' is the language user has selected.
// Set the preference
window.localStorage.setItem("language", selectedOption);
// Get the preference, anytime you want once set
window.localStorage.getItem("language")

Dropdown menu - save the choice on reload

I need to create popup language dropdown menu with country name, flag and link to the language version of the site. After user select menu item - it should take you to the needed url (language version of the page) and this choice should stay visible on the new page (after reload). Example of the menu - https://prnt.sc/sjumj8 (https://www.farfetch.com/shopping/women/items.aspx)
Here is an example of what I'm trying to create: https://jsfiddle.net/Okean/8x0atLpy/62/
<body>
<ul class="list-unstyled" id="select-lang">
<li class="init">[SELECT]</li>
<li data-value="value 1"> <img src="https://image.flaticon.com/icons/svg/197/197615.svg"> Language 1 </li>
<li data-value="value 2"> <img src="https://image.flaticon.com/icons/svg/197/197386.svg">Language 2 </li>
<li data-value="value 3"> <img src="https://image.flaticon.com/icons/svg/197/197484.svg">Language 3 </li>
<li data-value="value 4"> <img src="https://image.flaticon.com/icons/svg/197/197380.svg">Language 4 </li>
</ul>
</body>
<script>
$("ul").on("click", "li:not(.init)", function() {
allOptions.removeClass('selected');
$(this).addClass('selected');
$("ul").children('.init').html($(this).html());
allOptions.toggle();
});
window.onload = function() {
var selItem = sessionStorage.getItem("SelItem");
$('#select-lang').val(selItem);
}
$('#select-lang').change(function() {
var selVal = $(this).val();
sessionStorage.setItem("SelItem", selVal);
});
</script>
<style>
body{
padding:30px;
}
ul {
height: 30px;
width: 150px;
border: 1px #000 solid;
}
ul li { padding: 5px 10px; z-index: 2; }
ul li:not(.init) { float: left; width: 130px; display: none; background: #ddd; }
ul li:not(.init):hover, ul li.selected:not(.init) { background: #09f; }
li.init { cursor: pointer; }
a#submit { z-index: 1; }
li img {
width: 20px;
}
</style>
<ul> tag element won't ever trigger a .change event,
you can't even use li.val() as it doesn't have an actual value attribue.
So you need to workaround a little, something like this
$(document).ready(() => {
// cache selectors for better performance
const listItem = $("ul");
const listSelected = listItem.find('.init');
const allOptions = listItem.children('li:not(.init)');
listItem.on('click', '.init', () => {
listItem.children('li:not(.init)').toggle();
});
listItem.on('click', 'li:not(.init)', (e) => {
const that = $(e.target);
const setHTML = that.html();
allOptions.removeClass('selected');
that.addClass('selected');
listSelected.html(setHTML);
allOptions.toggle();
sessionStorage.setItem('SelItem', setHTML);
});
const selectItem = $("#select-lang");
const storedItem = sessionStorage.getItem('SelItem');
if (storedItem) {
listSelected.html(storedItem);
}
});
this should work as expected, storing target <li> HTML inside SelItem on sessionStorage

Is it possible to filter already fetched data with jQuery

I am using the Laravel framework and fetching data. Now I am trying to filter the data with Ajax and jQuery. But a couple problem that I am facing...
UPDATED 4
When I start filter, there is this error looping:
"/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 255,
"trace": [
{
"file": "/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 242,
"function": "methodNotAllowed",
"class": "Illuminate\Routing\RouteCollection",
"type": "->"
},
is there that I am missing something about the controller? or routing? Thank you for help!
Laravel Controller:
public function search(Request $request)
{
$q = $request->q;
$sortbyprice = $request->sortbyprice;
$region = $request->region;
$rooms = $request->rooms;
$price = $request->price;
$max = $request->input('max');
$min = $request->input('min');
$paginationData = [
'q' => $q
];
$estates = \DB::table('allestates')
->where('lat', '!=', '')
->where('lng', '!=', '')
->where('price', '!=', '')
->when($q, function($query, $q) use ($paginationData) {
$paginationData['q'] = $q;
return $query->where(function($query) use ($q) {
$query->where("building_name", "LIKE", "%" . $q . "%")
->orWhere("address", "LIKE", "%" . $q . "%")
->orWhere("company_name", "LIKE", "%" . $q . "%")
->orWhere("region", "LIKE", "%" . $q . "%")
->orWhere("rooms", "LIKE", "%" . $q . "%");
});
})
->when($sortbyprice, function($query, $order) use ($paginationData) {
if(!in_array($order, ['asc','desc'])) {
$order = 'asc';
}
$paginationData['sortbyprice'] = $order;
return $query->orderBy('price', $order);
}, function($query) {
return $query->orderBy('price');
})
->when($region, function($query, $regionId) use ($paginationData) {
$paginationData['region'] = $regionId;
return $query->where('region', $regionId);
})
->when($rooms, function($query, $roomsId) use ($paginationData) {
$paginationData['rooms'] = $roomsId;
return $query->where('rooms', "LIKE", "%" . $roomsId . "%");
})
->when($max, function($query, $max) use ($min, $paginationData) {
$paginationData['min'] = $min;
$paginationData['max'] = $max;
return $query->whereBetween('price', [$min, $max]);
})
// ->toSql()
->paginate(100);
$paginationData = array_filter($paginationData);
return view("home", compact('estates', 'q','paginationData'));
}
var displayList = $('#display-wrapper ol');
var selectedOptions = {
sortbyprice: '',
rooms: '',
region: ''
};
$('html').click(function () {
console.log(selectedOptions);
});
$('a.region').on('click', function () {
var selectValue = $(this).data('value');
$('#region').text(selectValue);
selectedOptions.region = selectValue;
fetchDataFromServer(selectedOptions);
});
$('a.rooms').on('click', function () {
var selectValue = $(this).data('value');
$('#rooms').text(selectValue);
selectedOptions.rooms = selectValue;
fetchDataFromServer(selectedOptions);
});
$('a.sortbyprice').on('click', function () {
var selectValue = $(this).text();
selectedOptions.sortbyprice = selectValue;
fetchDataFromServer(selectedOptions);
});
function serialize(options) {
var arr = [];
for (var key in options) {
arr.push(key + '=' + options[key]);
}
return encodeURI(arr.join('&'));
}
function fetchDataFromServer(options) {
$.ajax({
type: 'POST',
url: '/home',
data: serialize(options),
success: function (response) {
if (response.error) {
console.error(response.error);
} else {
console.log(response);
updateDisplay(displayList);
}
},
error: function (html, status) {
console.log(html.responseText);
console.log(status);
}
});
}
function updateDisplay(node, data) {
var template = data.reduce(function (acc, item) {
return acc + '<li><p>Region: ' + item.region + '</p><p>Price: ' + item.price + '</p><p>Rooms: ' + item.rooms + '</p></li>';
}, '');
node.empty();
node.append(template);
}
#filter-wrapper {
margin-top: 15px
}
#filter-wrapper ul {
list-style: none;
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul a {
display: block;
color: #333;
text-decoration: none;
font-weight: 700;
font-size: 12px;
line-height: 32px;
padding: 0 15px;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}
#filter-wrapper ul li {
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul li.current-menu-item {
background: lightblue;
}
#filter-wrapper ul li:hover {
background: #f6f6f6
}
#filter-wrapper ul ul {
display: none;
position: absolute;
top: 100%;
left: 0;
background: #fff;
padding: 0
}
#filter-wrapper ul ul li {
float: none;
width: 200px
}
#filter-wrapper ul ul a {
line-height: 120%;
padding: 10px 15px
}
#filter-wrapper ul ul ul {
top: 0;
left: 100%
}
#filter-wrapper ul li:hover>ul {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filter-wrapper">
<ul>
<li><a class="sortbyprice" href="javascript:" data-value="sortbyprice">Cheapest</a></li>
<li class="dropdown">
間取り
<ul class="init" name="rooms">
<li><a class="rooms" href="javascript:" data-value="1DK">1DK</a></li>
<li><a class="rooms" href="javascript:" data-value="2LDK">2LDK</a></li>
<li><a class="rooms" href="javascript:" data-value="3LDK">3LDK</a></li>
</ul>
</li>
<li class="dropdown">
エリア
<ul class="init" name="region">
<li><a class="region" href="javascript:" data-value="関西">関西</a></li>
<li><a class="region" href="javascript:" data-value="関東">関東</a></li>
<li><a class="region" href="javascript:" data-value="北海道">北海道</a></li>
</ul>
</li>
</ul>
</div>
<div id="display-wrapper">
<ol></ol>
</div>
Yes you can.
This is often done on the server, but if your data set is small enough it can work. If you set the filterable data points as data elements of your items you can just compare the selected value from the filter. jQuery's each function is one way to loop through the elements and you can then use the data function to access the appropriate data attribute.
$('#room-filter').on('change', function() {
const numRooms = $(this).val();
$('.card').each(function() {
if (numRooms && numRooms != $(this).data('rooms')) {
$(this).slideUp();
} else {
$(this).slideDown();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Rooms:
<select id="room-filter">
<option value="">Show All</option>
<option value="1">1 Room</option>
<option value="2">2 Rooms</option>
<option value="3">3 Rooms</option>
</select>
<div class="card text-left" data-rooms="1">
<div class="card-body d-flex" id="content-card">
<h2>Shack</h2>
<p class="main-text">1 room</p>
</div>
</div>
<div class="card text-left" data-rooms="1">
<div class="card-body d-flex" id="content-card">
<h2>Second Shack</h2>
<p class="main-text">1 room</p>
</div>
</div>
<div class="card text-left" data-rooms="3">
<div class="card-body d-flex" id="content-card">
<h2>Bungalo</h2>
<p class="main-text">3 rooms</p>
</div>
</div>
The main idea is to create a variable to store all the options selected by the user, and on each ajax request, you send the corresponding data to the server in order to get the filtered result.
I removed the hidden HTML form, and choose to use an object instead.
The ajax request in this code snippet is not working because there is no end-point '/home' for me to get the resources, but I think this will work on your machine.
As a side note, the id attribute should be unique, or else, the behavior might not be what you'd expected. And for the onclick handlers, if you have a lot of dropdowns, you should consider generating them with a loop instead of copy and pasting like I did, but for demo purposes, I will leave it as it is for now.
// a sample display
var displayList = $('#display-wrapper ol');
// create an object to store the selected options
var selectedOptions = {
sortbyprice: '',
rooms: '',
region: ''
};
// this event handler is for logging out the selectedOptions
// so that you can see what happens to the variable
// you should remove this in production
$('html').click(function () {
console.log(selectedOptions);
});
$('a.region').on('click', function () {
// I guess what you're trying to do here is to update the dropdown
// text into the selected value, e.g replace エリア with 関西
var selectValue = $(this).data('value');
$('#region').text(selectValue);
selectedOptions.region = selectValue;
fetchDataFromServer(selectedOptions);
});
$('a.rooms').on('click', function () {
var selectValue = $(this).data('value');
$('#rooms').text(selectValue);
selectedOptions.rooms = selectValue;
fetchDataFromServer(selectedOptions);
});
$('a.sortbyprice').on('click', function () {
// var selectValue = $(this).text();
// selectedOptions.sortbyprice = selectValue;
selectedOptions.sortbyprice = 'asc';
fetchDataFromServer(selectedOptions);
});
function fetchDataFromServer(options) {
$.ajax({
type: 'GET',
url: '/home',
data: options,
success: function (response) {
if (response.error) {
// sweetAlert("Oops...", response.data, "error");
console.error(response.error);
} else {
console.log(response);
// I assume the data structure of the response is something like
// var reponse = {
// data: [
// {
// price: 123,
// rooms: '1DK',
// region: '関西'
// },
// ......
// ]
// }
// This is an example function for updating the UI
// You can replace this function according to your needs
updateDisplay(displayList, response.data);
}
},
error: function (html, status) {
console.log(html.responseText);
console.log(status);
}
});
}
function updateDisplay(node, data) {
// build the html for the node(<ol> tag)
var template = data.reduce(function (acc, item) {
return acc + '<li><p>Region: ' + item.region + '</p><p>Price: ' + item.price + '</p><p>Rooms: ' + item.rooms + '</p></li>';
}, '');
// add the template to the node(<ol> tag)
node.empty();
node.append(template);
}
#filter-wrapper {
margin-top: 15px
}
/*
* I added this line for demo purpose
* Not sure whether you'll need this in your app
* Feel free to remove this
*/
#filter-wrapper::after {
content: '';
clear: both;
display: block;
}
#filter-wrapper ul {
list-style: none;
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul a {
display: block;
color: #333;
text-decoration: none;
font-weight: 700;
font-size: 12px;
line-height: 32px;
padding: 0 15px;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}
#filter-wrapper ul li {
position: relative;
float: left;
margin: 0;
padding: 0
}
#filter-wrapper ul li.current-menu-item {
background: lightblue;
}
#filter-wrapper ul li:hover {
background: #f6f6f6
}
#filter-wrapper ul ul {
display: none;
position: absolute;
top: 100%;
left: 0;
background: #fff;
padding: 0
}
#filter-wrapper ul ul li {
float: none;
width: 200px
}
#filter-wrapper ul ul a {
line-height: 120%;
padding: 10px 15px
}
#filter-wrapper ul ul ul {
top: 0;
left: 100%
}
#filter-wrapper ul li:hover>ul {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filter-wrapper">
<ul>
<li><a class="sortbyprice" href="javascript:" data-value="sortbyprice">Cheapest</a></li>
<li class="dropdown">
間取り
<ul class="init" name="rooms">
<li><a class="rooms" href="javascript:" data-value="1DK">1DK</a></li>
<li><a class="rooms" href="javascript:" data-value="2LDK">2LDK</a></li>
<li><a class="rooms" href="javascript:" data-value="3LDK">3LDK</a></li>
</ul>
</li>
<li class="dropdown">
エリア
<ul class="init" name="region">
<li><a class="region" href="javascript:" data-value="関西">関西</a></li>
<li><a class="region" href="javascript:" data-value="関東">関東</a></li>
<li><a class="region" href="javascript:" data-value="北海道">北海道</a></li>
</ul>
</li>
</ul>
</div>
<div id="display-wrapper">
<ol></ol>
</div>

Go to Specified text in ul li based select box

i want to have functionality such as that of select box, when using select box, if we type some keyword and that keyword happens to match in that select box, the pointer moves to the specified text, i want to achieve similar functionality here, following is my HTML
Get Value
<ul>
<li class="init">SELECT</li>
<li data-value="value 1">1</li>
<li data-value="value 2">2</li>
<li data-value="value 3">3</li>
</ul>
Following is my JS
$("ul").on("click", ".init", function() {
$(this).closest("ul").children('li:not(.init)').toggle();
});
var allOptions = $("ul").children('li:not(.init)');
$("ul").on("click", "li:not(.init)", function() {
allOptions.removeClass('selected');
$(this).addClass('selected');
$("ul").children('.init').html($(this).html());
allOptions.toggle();
});
$("#submit").click(function() {
alert("The selected Value is "+ $("ul").find(".selected").data("value"));
});
Following is my CSS
ul {
height: 30px;
width: 150px;
border: 1px #000 solid;
}
ul li { padding: 5px 10px; z-index: 2; }
ul li:not(.init) { float: left; width: 130px; display: none; background: #ddd; }
ul li:not(.init):hover, ul li.selected:not(.init) { background: #09f; }
li.init { cursor: pointer; }
a#submit { z-index: 1; }
Fiddle
http://jsfiddle.net/Starx/a6NJk/2/
Check out something like chosen or selectize. Download their files and add them to your site. if you go with Chosen you can initialize the plugin by adding .chosen-select to your form element:
<select class="chosen-select">
<option>Hello</option>
<option>Whats Up</option>
<option>How Are You</option>
<option>Nice to See You</option>
<option>Goodbye</option>
</select>
EXAMPLE

Changing Style of Parent LI in Collapsible Menu

This should be easy, but I'm having a hard time with it.
I have a simple collapsing menu that uses SPAN tags inside LI tags, the usual.
Here's the JavaScript:
var allSpan = document.getElementsByTagName('SPAN');
for (var i = 0; i < allSpan.length; i++) {
allSpan[i].onclick = function() {
if (this.parentNode) {
var childList = this.parentNode.getElementsByTagName('UL');
for (var j = 0; j < childList.length; j++) {
var currentState = childList[j].style.display;
if (currentState == "none") {
childList[j].style.display = "block";
} else {
childList[j].style.display = "none";
}
}
}
}
}
It works just fine in hiding and showing the nested ULs. What I'd like to do is add a piece of code that also changes the SPAN of the clicked-on parent LI item.
I'm thinking it would be something like:
if(currentState=="none") {
childList[j].style.display="block";
$(this).css('background-color', 'red');
}
else {
childList[j].style.display="none";
$(this).css('background-color', 'blue');
}
I'm sure I'm missing the obvious. Could somebody please point me in the right direction?
UPDATE
Sorry, I totally forgot there was more code at the bottom:
$(function() {
$('#menu').find('SPAN').click(function(e) {
$(this).parent().find('UL').toggle();
});
});
And here is the body of the HTML:
<style TYPE="text/css">
<!--
body { background: white;color: #000000;font-family:geneva; }
a:link { color: #ff8080 }
a:visited { color: #ff0000 }
a:active { color: #a05050 }
ul { margin:0;padding:0; }
li { list-style-type: none; }
ul li span { display:block;min-height:20px;background:blue;color:white;font-weight:bold;padding: 3px 8px 3px 8px;border-top:1px solid black;border-left:1px solid black;border-right:1px solid black;margin:0; }
li ul { display:none; }
li ul li span { background:#98ff33;padding: 3px 8px 3px 8px;color:black;font-weight:normal;display:block; }
li ul li:last-child span { border-bottom:1px solid black; }
-->
</style>
</head>
<body>
<UL id="menu">
<LI class="Category"><SPAN>Solid Tumors</SPAN><UL>
<LI class="subtopic"><SPAN>Anal Cancer</SPAN></LI>
<LI class="subtopic"><SPAN>Biliary Cancer</SPAN></LI>
<LI class="subtopic"><SPAN>Bladder Cancer</SPAN></LI>
</UL>
<LI class="Category"><SPAN>Hematologic Malignancies</SPAN><UL>
<LI class="subtopic"><SPAN>Acute Myeloid Leukemia</SPAN></LI>
<LI class="subtopic"><SPAN>Acute Promyelocytic Leukemia</SPAN></LI>
</UL>
<LI class="Category"><SPAN>Reviewers</SPAN><UL>
<LI class="subtopic"><SPAN>Physician Reviewers</SPAN></LI>
<LI class="subtopic"><SPAN>Pharmacy Reviewers </SPAN></LI>
</UL>
</UL>
A simple method would be to only toggle the class of the parent li element:
$(function () {
$('#menu SPAN').click(function (e) {
$(this).parent().toggleClass('open');
});
});
And then add then using CSS to manage the colors and the show/hide by adding the following css:
#menu li.open > span {
background-color: red
}
#menu li.open ul {
display: inline
}
see: http://jsfiddle.net/3TTDJ/
Note: if you only want to do this for the first menu level and not recursive, you'll want to specify that in the selector using immediate child selector '#menu > li > SPAN':
$(function () {
$('#menu > li > SPAN').click(function (e) {
$(this).parent().toggleClass('open');
});
});
see: http://jsfiddle.net/tleish/3TTDJ/2/
Below changes the span background color or the parent listitem
http://jsfiddle.net/tuusT/2/
$('#menu').find('SPAN').click(function(e){
$('#menu').find('.active').removeClass("active");
$(this).parents(".Category").children("span:first").addClass("active")
$(this).parent().find('UL').toggle();
});

Categories