How to remove element in jquery sortable? - javascript

My HTML Code is like this :
<div class="content">
box 1 (Customer)
<ol class='example mauDIDROP vertical'>
<li>Valentino Rossi</li>
<li>David Beckham</li>
<li>Eden Hazard</li>
<li>Lionel Messi</li>
<li>Christiano Ronaldo</li>
<li>Frank Lampard</li>
</ol>
</div>
<div class="content">
<form id="myForm" action="" method="POST">
box 2 (Room Type)
<br>
<select id="room_type">
<option value="1">Single Room</option>
<option value="2">Double Room</option>
<option value="3">Twin Room</option>
</select>
<input type="button" value="Add" style="margin-top: -10px;" id="add_room">
<ol class="example areaDROP vertical" id="room_list">
<li class="room_number msg1" id="room_remove11">Deluxe Room<div class="room-remove"><i class="fa fa-times"></i></div><ol><li id="room_remove21">John Terry<div class="room-remove"><i class="fa fa-times"></i></div></li></ol></li>
<li class="room_number msg1" id="room_remove12">Family Room<div class="room-remove"><i class="fa fa-times"></i></div><ol><li id="room_remove22">Jose Mourinho<div class="room-remove"><i class="fa fa-times"></i></div></li></ol></li>
</ol>
<button type="submit">Save</button>
</form>
</div>
My Javascript is like this :
function delete_room(id){
$('#room_remove'+id).remove();
}
$(document).ready(function(){
$("ol.mauDIDROP").sortable({
group: '.example'
});
$("ol.areaDROP").sortable({
group: '.example',
});
var room_type_number = 5;
$('#add_room').click(function(){
var text = $("#room_type option:selected").html();
var room_type_id = $.trim($('#room_type').val());
$('#room_list').append('<li class="room_number msg" id="room_remove'+(++room_type_number)+'" data-id="'+room_type_id+'" data-name="'+text+'">'+text+'<div class="room-remove"><i class="fa fa-times"></i></div><ol></ol></li>');
$("ol.mauDIDROP").sortable({
group: '.example'
});
$("ol.areaDROP").sortable({
group: '.example',
});
});
});
Demo is like this : https://jsfiddle.net/oscar11/4wnfnz6z/1/
When I click on the close icon, the selected element successfully deleted.
But what I want:
When I click on the close icon, the selected element removed and deleted customer element appears in box 1.
For example : http://imgur.com/rEzryt3
When I click on the close icon(deluxe room), it will look like this : http://imgur.com/YpkBTKH
How to keep deleted customer element in moving towards the box 1?
Any suggestion to solve my problem?
Thank you

You can change a bit your delete_room function so it would grab the names of customers from the room you are removing and then append them as lis to your left container:
function delete_room(id){
var customers = '';
$('#room_remove'+id).find('li').each( function() {
customers += '<li>'+$(this).text()+'</li>';
});
$('#room_remove'+id).remove();
$('ol.example.mauDIDROP.vertical').append(customers);
}
Check fiddle: Fiddle

This approach have better performance, cause you are setting the find to a var and doing a loop instead of doind a loop with the find.
var child = $('#room_remove'+id).find('li');
if(child.length > 0){
var li = "";
child.each(function(){
li += "<li>"+$(this).text()+"</li>";
});
}
$(".mauDIDROP").append($(li));

Related

Add new element into DOM with JavaScript

I am struggling with adding new "button" element into my "list". I was trying to append or someting els but doesn't work. It is not usual ul to li. If you ask why button parent it is form bootstrap list-group
UPDATE JS. IT is now adding "button but not corectlly.
<div class="list-group">
<button type="button" class="list-group-item">
<ul class="desc">
<li class="t-desc50">Add Device</li>
<li class="t-desc55"><i class="fa fa-plus fa-2x" aria-hidden="true"></i></li>
</ul>
</button>
<button type="button" class="list-group-item" id="new-item>
<ul class="desc">
<li class="t-desc">Lamp</li>
<li class="t-desc2">5 kwH</li>
<li class="t-desc3"><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></li>
</ul>
</button>
<button type="button" class="list-group-item" id="new-item>
<ul class="desc">
<li class="t-desc">AC</li>
<li class="t-desc2">5 kwH</li>
<li class="t-desc3"><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></li>
</ul>
</button>
</div>
JS
document.querySelector('.fa-plus').addEventListener('click', addItem
);
function addItem() {
var list = document.getElementById("list-group");
var li = document.createElement("button");
li.setAttribute('id', li);
li.appendChild(document.createTextNode(li));
list.appendChild(li);
}
If you want to add an element to the dom, you can use :
var element = document.createElement(tagName);
https://developer.mozilla.org/fr/docs/Web/API/Document/createElement
Then append your element.
You can add event listener to element, and add class before if you need.
Comment answer
The code you need is probably something like that :
function addItem() {
var list = document.getElementById('list-group')
//Button
var button = document.createElement('button');
button.classList.add("list-group-item");
//Ul
var ul = document.createElement('ul');
ul.classList.add("desc");
//li
var liFirst = document.createElement('li');
var liSecond = document.createElement('li');
var liThird = document.createElement('li');
liFirst.innerHTML = "Lamp"
liSecond.innerHTML = "5 kwH"
//Label
var label = document.createElement('label');
label.classList.add("switch");
var input = document.createElement('input');
input.type = 'checkbox';
var span = document.createElement('span');
span.classList.add("slider");
span.classList.add("round");
label.append(input)
label.append(span)
liThird.append(label)
ul.append(liFirst)
ul.append(liSecond)
ul.append(liThird)
button.append(ul)
list.append(button)
}
You need to pass the function as argument instead of calling it:
// wrong:
document.querySelector('.fa-plus').addEventListener('click', addElement());
// right:
document.querySelector('.fa-plus').addEventListener('click', addElement);
addEventListener expects a callback function, if you call the function first, you are sending the result of the function as argument, which is wrong.
You need to pass the addElement function instead, so the addEventListener calls it.
got it!
function addItem() {
var list = document.getElementById('list-group')
var button = document.createElement('button');
var ul = document.createElement('ul');
var liFirst = document.createElement('li');
var liSecond = document.createElement('li');
var liThird = document.createElement('li');
button.classList.add("list-group-item");
ul.classList.add("desc");
liFirst.classList.add("t-desc")
liSecond.classList.add("t-desc2")
liThird.classList.add("t-desc3")
liFirst.innerText = 'TV'
liSecond.innerText = '5kwh'
liThird.innerHTML = `<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>`
ul.append(liFirst)
ul.append(liSecond)
ul.append(liThird)
button.append(ul)
list.append(button)
}
There are several semantic errors in both the markup and the code. Firstly, <button type="button" class="list-group-item" id="new-item> misses the closing double quotes. Secondly, one should not use an id twice as the OP's example does with id="new-item. At third addEventListener misses its 3rd argument.
Besides that it will be hard if not impossible to capture any click event on the fa-plus classified <i/> element; one should use the whole button instead ... that's what a button is for.
Additionally one might rethink how to retrieve/query the structure one wants to add the new element to. I would suggest a more generic approach that retrieves the top most group parent from within the structure where the click event did occur, thus one can make use of more than just on list-group classified element.
Having sanitized the code the OP'S given example then might look similar to this ...
function getClosestParentByClassName(elm, className) {
while (elm && !elm.classList.contains(className)) {
elm = elm.parentNode;
}
return elm;
}
function addItem(evt) {
//console.log(evt.currentTarget);
var
groupParent = getClosestParentByClassName(evt.currentTarget, 'list-group'),
itemBlueprint = groupParent && groupParent.querySelector('.list-group-item.new-item'),
newGroupItem = (itemBlueprint && itemBlueprint.cloneNode(true)) || createDefaultItem();
//console.log(groupParent, itemBlueprint, newGroupItem);
if (newGroupItem) {
// do whatever needs to be done in order to place the right content into this structure.
groupParent.appendChild(newGroupItem);
}
}
getClosestParentByClassName(document.querySelector('.fa-plus'), 'list-group-item').addEventListener('click', addItem, false);
function createDefaultItem() {
var
renderContainer = document.createElement('div');
renderContainer.innerHTML = [
'<button type="button" class="list-group-item new-item">'
, '<ul class="desc">'
, '<li class="t-desc">#missing t-desc</li>'
, '<li class="t-desc2">#missing t-desc2</li>'
, '<li class="t-desc3">'
, '<label class="switch">'
, '<input type="checkbox">'
, '<span class="slider round"></span>'
, '</label>'
, '</li>'
, '</ul>'
, '</button>'
].join('');
return renderContainer.querySelector('button');
}
.as-console-wrapper { max-height: 100%!important; top: 0; }
<div class="list-group">
<button type="button" class="list-group-item">
<ul class="desc">
<li class="t-desc50">Add Device</li>
<li class="t-desc55"><i class="fa fa-plus fa-2x" aria-hidden="true"></i></li>
</ul>
</button>
<button type="button" class="list-group-item new-item">
<ul class="desc">
<li class="t-desc">Lamp</li>
<li class="t-desc2">5 kwH</li>
<li class="t-desc3">
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
</li>
</ul>
</button>
<button type="button" class="list-group-item new-item">
<ul class="desc">
<li class="t-desc">AC</li>
<li class="t-desc2">5 kwH</li>
<li class="t-desc3">
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
</li>
</ul>
</button>
</div>

Unable to set the value of input field onclick

I have created this custom dropdown which has custom radio buttons.
I get the value of the selected radio button and set it to span tag successfully.
What i am not getting is : i want to set the same value in the input field that is present in the dropdown, but the value is not getting set.
i use pure js as well as jquery to do so but the value is alerting and not setting into the input field.
code is live here: http://thekabir.in/onsitego-planlisting2017/index.html
Steps: click on check brands dropdown and select any brand..
jquery and js used are
//filters dropdown
function DropDown(el) {
this.dd = el;
this.placeholder = this.dd.children('span');
this.opts = this.dd.find('div.dropdown li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.dd.on('click',function(){
$(this).toggleClass("active");
$(this).parent().toggleClass("border-active");
$('.filters').toggleClass('border-bottom');
$(this).children('.dropdown').css('width',$(window).width());
var deID = $(this);
if(deID[0].id == 'devicebrand')
{
$('#devicebrand i.icon-down-arrow-1').addClass('icon-up-arrow-1').removeClass('icon-down-arrow-1');
}
return false;
});
obj.opts.on('click',function(e){
// e.preventDefault();
$(this).parent().addClass('hidden');
$(this).addClass('active');
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
var currentID = $(this).parents('div.wrapper-dropdown-3')[0].id;
if(currentID == 'devicebrand')
{
$('#devicebrand.wrapper-dropdown-3 .dropdown li').removeClass('active');
$('#devicebrand.wrapper-dropdown-3 .dropdown li span').removeClass('icon-selected-radio-yellow').addClass('icon-oval-3-copy-3');
$('#devicebrand i.icon-up-arrow-1').addClass('icon-tick-filled').removeClass('icon-up-arrow-1');
$('.more-brands').addClass('hidden');
$('.covered').removeClass('hidden');
$('#manual-brand-input').val(obj.val);
}
$(this).children('span').removeClass('icon-oval-3-copy-3').addClass('icon-selected-radio-yellow');
$(this).parent().toggleClass("border-active");
$('.dropdown input').val('');
e.stopPropagation();
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
};
$(function() {
var dd = new DropDown( $('#devicebrand') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-3').removeClass('active');
});
});
Html :
<div class="filter check-brand">
<div id="devicebrand" class="wrapper-dropdown-3" tabindex="1">
<i class="icon icon-brand"></i>
<span data-val="-1">check brand </span>
<div class="dropdown brand">
<span class="icon-cross-it"></span>
<div class="side-info">
<p class="SELECT-YOUR-MOBILE-P">SELECT YOUR MOBILE BRAND </p>
<p class="One-line-to-explain">One line to explain why he needs to select his city. Along with more information.</p>
</div>
<div class="city-selection">
<ul>
<li><span class="icon-oval-3-copy-3"></span>HTC</li>
<li><span class="icon-oval-3-copy-3"></span>motorola</li>
<li><span class="icon-oval-3-copy-3"></span>xiaomi</li>
<li><span class="icon-oval-3-copy-3"></span>LG</li>
<li><span class="icon-oval-3-copy-3"></span>samgsung</li>
<li><span class="icon-oval-3-copy-3"></span>sony</li>
<li><span class="icon-oval-3-copy-3"></span>huawei</li>
<li><span class="icon-oval-3-copy-3"></span>google pixel</li>
<li><span class="icon-oval-3-copy-3"></span>nokia</li>
<li><span class="icon-oval-3-copy-3"></span>le-eco</li>
</ul>
<div class="more-brands">
<a class="more-brands-btn" href="javascript:void(0);">+ 254 Brands</a>
</div>
<div class="manual-brand">
<input placeholder="Enter your brand if not found above " id="manual-brand-input" class="manual-brand-input ui-autocomplete-input" value="" autocomplete="off" type="text"><span class="icon-shape_4"></span>
<ul id="ui-id-1" tabindex="0" class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front" style="display: none;"></ul></div>
<div class="covered hidden">
<p><span class="icon-tick"></span>Congratulations! Free Pick & Drop service available in your city</p>
<p><span class="icon-tick"></span>400 Service centers near you</p>
<p><span class="icon-tick"></span>20% of people bought this near your locality</p>
<p><span class="icon-tick"></span>3days is average repair time in your area.</p>
</div>
<div class="not-covered hidden">
<p><span class="icon-not-covered-tick"></span>Sorry, we are currently present in India. We don’t cover your City.</p>
<p>We can briefly state here why we dont cover particular city. Or if at all we are in process of including it.</p>
</div>
</div>
</div>
<i class="icon-down-arrow-1"></i>
<i class="icon-orange-cross hidden"></i>
</div>
</div>
Here is the fiddle for the same.
https://jsfiddle.net/kvab7wyd/1/
UPDATE
Applied my answer to OP's Fiddle
Store your value in a variable, then set the input's value equal to the variable. The way you had it was not working because document.getElementById('input').value is plain JavaScript expression and $(this).attr(data-) is jQuery expression, if you mix them, you must take dereference the jQuery by using $(obj).get() or dot notation $(obj)[0], although I'm not entirely sure it would be worth the trouble in doing so. BTW use e.preventDefault() when using links that don't go anywhere, that'll stop that irritating jumping when clicking them. I also used .data() instead of .attr() it's the same result either way but .data() looks cleaner.
SNIPPET
$('.dropdown li a').on('click', function(e){
var data = $(this).data('val');
e.preventDefault();
document.getElementById('manual-brand-input').value = data;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter check-brand">
<div id="devicebrand" class="wrapper-dropdown-3" tabindex="1">
<i class="icon icon-brand"></i>
<span data-val="-1">check brand </span>
<div class="dropdown brand">
<span class="icon-cross-it"></span>
<div class="side-info">
<p class="SELECT-YOUR-MOBILE-P">SELECT YOUR MOBILE BRAND </p>
<p class="One-line-to-explain">One line to explain why he needs to select his city. Along with more information.</p>
</div>
<div class="city-selection">
<ul>
<li><span class="icon-oval-3-copy-3"></span>HTC</li>
<li><span class="icon-oval-3-copy-3"></span>motorola</li>
<li><span class="icon-oval-3-copy-3"></span>xiaomi</li>
<li><span class="icon-oval-3-copy-3"></span>LG</li>
<li><span class="icon-oval-3-copy-3"></span>samgsung</li>
<li><span class="icon-oval-3-copy-3"></span>sony</li>
<li><span class="icon-oval-3-copy-3"></span>huawei</li>
<li><span class="icon-oval-3-copy-3"></span>google pixel</li>
<li><span class="icon-oval-3-copy-3"></span>nokia</li>
<li><span class="icon-oval-3-copy-3"></span>le-eco</li>
</ul>
<div class="more-brands">
<a class="more-brands-btn" href="javascript:void(0);">+ 254 Brands</a>
</div>
<div class="manual-brand">
<input placeholder="Enter your brand if not found above " id="manual-brand-input" class="manual-brand-input ui-autocomplete-input" value="" autocomplete="off" type="text"><span class="icon-shape_4"></span>
<ul id="ui-id-1" tabindex="0" class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front" style="display: none;"></ul></div>
<div class="covered hidden">
<p><span class="icon-tick"></span>Congratulations! Free Pick & Drop service available in your city</p>
<p><span class="icon-tick"></span>400 Service centers near you</p>
<p><span class="icon-tick"></span>20% of people bought this near your locality</p>
<p><span class="icon-tick"></span>3days is average repair time in your area.</p>
</div>
<div class="not-covered hidden">
<p><span class="icon-not-covered-tick"></span>Sorry, we are currently present in India. We don’t cover your City.</p>
<p>We can briefly state here why we dont cover particular city. Or if at all we are in process of including it.</p>
</div>
</div>
</div>
<i class="icon-down-arrow-1"></i>
<i class="icon-orange-cross hidden"></i>
</div>
</div>
Main change is here: $('.dropdown input').val($(this).find('a').data('val'));
//filters dropdown
function DropDown(el) {
this.dd = el;
this.placeholder = this.dd.children('span');
this.opts = this.dd.find('div.dropdown li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.dd.on('click',function(){
$(this).toggleClass("active");
$(this).parent().toggleClass("border-active");
$('.filters').toggleClass('border-bottom');
$(this).children('.dropdown').css('width',$(window).width());
var deID = $(this);
if(deID[0].id == 'devicebrand')
{
$('#devicebrand i.icon-down-arrow-1').addClass('icon-up-arrow-1').removeClass('icon-down-arrow-1');
}
return false;
});
obj.opts.on('click',function(e){
// e.preventDefault();
$(this).parent().addClass('hidden');
$(this).addClass('active');
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
var currentID = $(this).parents('div.wrapper-dropdown-3')[0].id;
if(currentID == 'devicebrand')
{
$('#devicebrand.wrapper-dropdown-3 .dropdown li').removeClass('active');
$('#devicebrand.wrapper-dropdown-3 .dropdown li span').removeClass('icon-selected-radio-yellow').addClass('icon-oval-3-copy-3');
$('#devicebrand i.icon-up-arrow-1').addClass('icon-tick-filled').removeClass('icon-up-arrow-1');
$('.more-brands').addClass('hidden');
$('.covered').removeClass('hidden');
}
$(this).children('span').removeClass('icon-oval-3-copy-3').addClass('icon-selected-radio-yellow');
$(this).parent().toggleClass("border-active");
console.log($(this).data('val'));
$('.dropdown input').val($(this).find('a').data('val'));
e.stopPropagation();
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
};
$(function() {
var dd = new DropDown( $('#devicebrand') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-3').removeClass('active');
});
});
You can try this:
$('.dropdown li a').click(function(e){
$("#manual-brand-input").val($(this).attr('data-val'));
});
There was a small error in my code.
$('.dropdown input').val('');
this was causing the value to be empty.
Sorry guys.

Pop selection off dropdown menu

I have a question about popping selection from dropdown off the menu. I have a dropdown that gets dynamically populated with people's names, and I'd like the name selected to pop off the drop down menu and appear in a div next to it. The dropdown menu:
<div class="col-md-4">
<div class="dropdown">
<button style="width: 100%;" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Group Members
<span class="caret"></span></button>
<ul class="dropdown-menu scrollable-menu" role="menu">
{{#each users}}
<li data-uid={{this.u_id}}>{{this.full_name}}</li>
{{/each}}
</ul>
</div>
</div>
And the div I'd like the information (name) to appear:
<div class="col-lg-4">
<h2 class="text-center" style="margin-top: 0;">Selected Group Members</h2>
<ul class="list-unstyled">
<li data-uid={{this.u_id}} class="text-center">{{this.full_name}}</li>
</ul>
</div>
I'm imagining this can be done with some jQuery, which I'm unfortunately not too great at, so I'm not quite sure how to do this. Any help is appreciated!
This should does the work. Please check.
// selected element
var selections = [];
// container that holds selections
var listContainer = $('.container .list-unstyled');
// sorting array of objects by provided field
var sortBy = function (arr, field) {
return arr.sort(function (a, b) {
if (a[field].toLowerCase() < b[field].toLowerCase()) return -1;
if (a[field].toLowerCase() > b[field].toLowerCase()) return 1;
return 0;
});
};
// redraw list on container
var reorder = function(){
listContainer.html('');
for(var i = 0; i < selections.length; i++){
listContainer.append('<li data-uid=' + selections.id + '>' + selections.value + '</li>');
}
}
// list items click handler
$('ul.list-unstyled li').click(function(){
selections.push({
id: $(this).attr('data-uid'),
value: $(this).text()
});
selections = sortBy(selections, 'name');
});

how to delete object in an array with filter used? AngularJS

I have something like an input to add items into either column 1 or column 2 and each time adding the items, the column will show up what is added right away with an 'X' beside it so if you want to delete the item just click on 'X'. At first I wasn't thinking much so I used an easy way to remove the HTML but then I realized, that's just removing the HTML (There's also a search input if I type something into search and clear the search, all items will show again). This is when I realized just removing the HTML is a mistake that I need to remove the object too but how can I make it so it'll delete the right object in the array?
My angular script
angular.module("addItemApp", [])
.controller("toDoCtrl", function ($scope) {
$scope.items = [];
$scope.addItem = function (item) {
console.log(item);
$scope.items.push(angular.copy(item));
console.log($scope.items);
};
$scope.remove = function (item) {
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
});
my html
<div class="row">
<div class="col-xs-6 col-sm-4 left-column">
<div class="input-item">
<input type="text" placeholder="Enter Item" ng-model="item.name" class="enter-item">
<select class="column-select" ng-model="item.pos">
<option value="default" selected>Choose Column</option>
<option value="column1">Column 1</option>
<option value="column2">Column 2</option>
</select>
<button class="add-button" type="button" ng-click="addItem(item)">Add Item</button>
</div>
<div class="search-item">
<label for="search">Search An Item</label>
<div class="search-input">
<input ng-model="query" type="text" placeholder="Search" id="search"><span class="fa fa-search icon-search"></span>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4">
<h3 class="column-header column1">
Column 1
</h3>
<ul ng-repeat="item in items | filter:{ pos: 'column1' } | filter:query">
<li>{{item.name}}
<button remove-on-click ng-click="remove()" class="remove-button fa fa-times"></button>
</li>
</ul>
</div>
<!-- Optional: clear the XS cols if their content doesn't match in height -->
<div class="clearfix visible-xs-block"></div>
<div class="col-xs-6 col-sm-4">
<h3 class="column-header column2">
Column 2
</h3>
<ul ng-repeat="item in items | filter:{ pos: 'column2' } | filter:query">
<li>{{item.name}}
<button remove-on-click ng-click="remove()" class="remove-button fa fa-times"></button>
</li>
</ul>
</div>
</div>
Thanks in advance everyone.
you can do it in two ways -
1
$scope.remove = function(item) {
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
<button ng-click="remove(item)"></button>
2
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
<button ng-click="remove($index)"></button>
Please note that, when filter is applied, the $index may not be the one you should use to remove, better go with first approach. I have given example of $index for your reference.
<button ng-click="remove(item)"></button>
should work, since item is defined earlier in the ng-repeat and you already have a remove function defined on your $scope.

jQuery show and hide dynamic classes not working

I am trying to hide and show div's displayed on my page with a select element however having a bit of trouble as I can't seem to get the jQuery to function.
I am listing results from my SQL table using PHP that currently displays every row onto my page and prints them into a list.
I want to make the jQuery hide the div's that don't have a class that matches the select option that is selected.
Here is an example of the listing template that echo's out all of the MySQL results and displays them into a template and is then looped to display every row on the table:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container ' . $row["Make"] . '">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
The 'Make' is added to the listing-container div to add a class to be able to filter the results with jQuery.
Here is the form with the select element I am using:
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option>'.$make["Make"].'</option>
';
} ?>
</select>
<select class="form-control last-select select-box">
<option value="model-any">Model (Any)</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
</form>
As you can see the select option contains the 'Make' and is looped.
So down to the jQuery:
<script>//Wait for DOM to load
(function() {
$(“.select-box”).change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(“.listing-container”).not(“.” + make).hide();
});
});</script>
So in theory this should work but for some reason it isn't, can anybody notice anything that might be wrong?
I have placed my script below the core jQuery in my footer and it still doesn't work.
Here is a live example: http://www.drivencarsales.co.uk/used-cars.php
Looks like you're using the wrong quotes in the source code of that page try replacing them with "
//Wait for DOM to load
$(function() {
$(".select-box").change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(".listing-container").not("." + make).hide().next().hide();
});
});
Edit
You also need a $ before the function
If I understand you correctly ↓ working code ↓
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('div.listing-container.'+make+",div.listing-container."+make+" + div.listing-container-spec").show();
$('div.listing-container:not(.'+make+'),div.listing-container:not(.'+make+') + div.listing-container-spec').hide();
});
});
And shorter code (but slower):
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('.listing-container.'+make+",.listing-container."+make+" + div").show();
$('.listing-container:not(.'+make+'),.listing-container:not(.'+make+') + div').hide();
});
});
P.S.You miss value attribute (but in live example everything ok):
echo '<option value="'.$make["Make"].'">'.$make["Make"].'</option>';

Categories

Resources