I am looking for a component like this to be included in my project:
http://geodan.github.io/duallistbox/sample-100.html
I want to install it with npm.
The problem is that I tested some of the examples which are over there, but without success (I get exceptions, or there is no npm, only bower)
These are the examples I tested.
https://github.com/alexklibisz/angular-dual-multiselect-directive
https://github.com/frapontillo/angular-bootstrap-duallistbox
http://www.bootply.com/mRcBel7RWm
Any recommendations about one with AngularJs, Bootstrap, and npm?
This might solve your requirement: Dual list Box
app.js
angular.module('plunker', [])
.controller('MainCtrl', function($scope, utils) {
$scope.list1 = [],
$scope.list2 = [];
utils.insertData($scope.list1, 5);
})
.factory('utils', function Utils() {
return {
insertData: function(list, numItems) {
for (var i = 0; i < numItems; i++) {
list.push({
id: i + 1,
title: 'item' + (i + 1)
});
}
},
getIndexesFromList: function(list) {
var newList = [];
for (var i in list) {
if (typeof list[i].id === "number" && newList.indexOf(list[i].id) === -1) newList.push(list[i].id)
}
return newList;
},
getAllSelectedItems: function(list) {
var newList = [];
newList = list.filter(function(el) {
return el.active === true;
});
return newList;
},
addListIfNoExists: function(list2, newListToAppend) {
var indexes = this.getIndexesFromList(list2);
var newList = [];
for (var i in newListToAppend) {
if (indexes.indexOf(newListToAppend[i].id) === -1) list2.push(newListToAppend[i])
}
return list2;
}
}
})
.directive('dualList', function(utils) {
function _controller($scope) {
$scope.selectAllItem = function(list, checked) {
list.map(function(item) {
item.active = checked
return item;
});
};
$scope.getAllSelectedItems = function(list) {
return utils.getAllSelectedItems(list);
}
$scope.moveItemToRightList = function() {
var newListToAppend = $scope.list1.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list1 = $scope.list1.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(el.id) === -1;
});
$scope.list2 = utils.addListIfNoExists($scope.list2, newListToAppend);
if ($scope.list1.length === 0) $scope.checked1 = false;
}
};
$scope.moveItemToLeftList = function() {
var newListToAppend = $scope.list2.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list2 = $scope.list2.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(parseInt(el.id)) === -1;
});
$scope.list1 = utils.addListIfNoExists($scope.list1, newListToAppend);
if ($scope.list2.length === 0) $scope.checked2 = false;
}
};
}
return {
restrict: "E",
scope: true,
controller: _controller,
templateUrl: "dualList.html"
};
});
dualList.html
<div class="container">
<br />
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked1"
ng-click="selectAllItem(list1, checked1)">
Todo {{getAllSelectedItems(list1).length}}/{{list1.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search1"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list1|filter: search1">{{item.title}}</a>
</ul>
<p ng-if="(list1 | filter:search1).length == 0">Sin Datos</p>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button ng-click="moveItemToLeftList()"
class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"></span>
</button>
<button ng-click="moveItemToRightList()"
class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked2"
ng-click="selectAllItem(list2, checked2)">
Todo {{getAllSelectedItems(list2).length}}/{{list2.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search2"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list2|filter: search2">{{item.title}}</a>
</ul>
<p ng-if="(list2 | filter:search2).length == 0">Sin Datos</p>
</div>
</div>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.angularjs.org/1.3.0/angular.js"></script>
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" />
<link data-require="font-awesome#*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<dual-list data-list1="list1" data-list2="list2"></dual-list>
</body>
</html>
style.css
.dual-list .list-group {
margin-top: 8px;
}
.list-arrows {
padding-top: 100px;
}
.list-arrows button {
margin-bottom: 20px;
}
.list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus {
border-color: white;
}
.input-group-addon {
top: 0;
}
I think this link will help you.
Try this npm for angular 2/4 just you need to install with npm
https://www.npmjs.com/package/ng2-dual-list-box
Related
so i'm currently trying to build search icon on the header clickable where you're able to search for, in this case, pokemon names, however i keep getting a console error
searchQuery.value undefined
Not sure why because the code looks valid.
Also, when you click on the search icon the icon goes above it and once you hit submit on the input it duplicates. I'm sure it's all connected the bug.
No sure why this is happening and would greatly appreciate any advice to fix this.
let pokemonRepository = (function() {
let pokemonList = [];
// API
let apiUrl = "https://pokeapi.co/api/v2/pokemon/?limit=150";
let searchIcon = $(".btn-outline-secondary");
let modalContainer = $(".modal");
let modalDialog = $(".modal-dialog");
let modalContent = $(".modal-content");
let modalBody = $(".modal-body");
let modalTitle = $(".modal-title");
let modalHeader = $(".modal-header");
let modalClose = $(".btn-close");
let listItemArray = $("li");
function add(pokemon) {
if (
typeof pokemon === "object" &&
"name" in pokemon &&
"detailsUrl" in pokemon
) {
pokemonList.push(pokemon);
} else {
console.error("pokemon is not correct");
}
}
function getAll() {
return pokemonList;
}
// filters through pokemon names
function search(pokemonName) {
return pokemonList.filter((pokemon) => pokemon.name === pokemonName);
}
// Function adds a list of pokemon
function addListItem(pokemon) {
let pokemonDisplay = $(".list-group-horizontal");
// Creates li element
let listItem = $("<li>");
listItem.addClass(
"list-group-item text-center col-sm-6 col-md-4 border border-secondary bg-image img-fluid"
);
// Creates h1 for Pokemon Name
let listTitle = $("<h1>");
listTitle.html(`${pokemon.name}`);
listTitle.addClass("display-6");
// Creates div which holds sprites
let listImg = $("<div>");
loadDetails(pokemon).then(function() {
listImg.append(
`<img src=${pokemon.imageUrlFront} alt="${pokemon.name} sprite"/>`
);
});
let listButton = $("<button>");
listButton.text("show More");
// Added Bootstrap Utility Class
listButton.addClass("mp-2 btn btn-secondary");
listButton.attr("type", "button");
listButton.attr("data-bs-toggle", "modal");
listButton.attr("data-bs-toggle", "#pokemonModal");
listItem.append(listTitle);
listItem.append(listImg);
listItem.append(listButton);
pokemonDisplay.append(listItem);
buttonEvent(listButton, pokemon);
}
function buttonEvent(listButton, pokemon) {
listButton.on("click", () => {
showDetails(pokemon);
});
}
function showDetails(pokemon) {
loadDetails(pokemon).then(() => {
// Clears existing content
modalContainer.empty();
modalTitle.addClass("modal-title h5 col-sml-3");
let pokemonType = {
fire: "text-danger",
grass: "text-success",
water: "text-primary",
electric: "text-warning",
flying: "text-info",
poison: "text-secondary",
};
pokemon.types.forEach((type) =>
modalTitle.addClass(pokemonType[type.type.name])
);
modalTitle.html(`${pokemon.name}`);
modalBody.html(`
Entry: ${pokemon.id}<br>
Height: ${pokemon.height}<br>
Weight: ${pokemon.weight}<br>
Types: ${pokemon.types[0].type.name}`);
if (pokemon.types.length === 2) {
modalBody.innerHTML += `, ${pokemon.types[1].type.name}`;
}
modalBody.innerHTML += `<br>Abilities: ${pokemon.abilities[0]}.ability.name}`;
if (pokemon.abilities.length === 2) {
modalBody.innerHTML += `, ${pokemon.abilities[1]}.ability.name}`;
}
modalBody.append(`<br>
<img src=${pokemon.imageUrlFront} alt="${pokemon.name} front sprite">
<img src=${pokemon.imageUrlBack} alt="${pokemon.name} back sprite">
<br>
`);
modalDialog.append(modalContent);
modalContent.append(modalHeader);
modalHeader.append(modalTitle);
modalHeader.append(modalClose);
modalContent.append(modalBody);
modalContainer.append(modalDialog);
});
modalContainer.modal("show");
}
modalContainer.on("shown.bs.modal", () => {
// Jquery eventlistener
modalClose.on("click", () => {
modalContainer.removeClass("fade");
modalContainer.modal("hide");
listItemArray[0].children().click();
});
});
searchIcon.on("click", () => {
// fetching .d-flex class in form
let bodyHeader = $(".d-flex");
// returns the number of child elements
if (bodyHeader.length === 1) {
//creates input element
let searchQuery = $("<input>");
searchQuery.attr("placeholder", "Pokemon Name");
searchQuery.attr("type", "search");
searchQuery.attr("aria-label", "search Pokemon Name");
searchQuery.addClass("form-control my-3 ps-2 col-sm");
searchIcon.blur();
searchQuery.focus();
bodyHeader.append(searchQuery);
searchQuery.on("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
for (let i = 0; i < listItemArray.length; i++) {
if (
902 >
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] &&
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] > 42
) {
listItemArray[i].children().last().click();
}
}
for (let i = 0; i < listItemArray.length; i++) {
if (listItemArray[i].text().split("\n")[0] === searchQuery.value) {
setTimeout(function() {
listItemArray[i].children().last().click();
}, 5);
}
}
}
});
}
});
// Fetches data from API
function loadList() {
return fetch(apiUrl)
.then(function(response) {
return response.json();
})
.then(function(json) {
json.results.forEach((item) => {
let pokemon = {
name: item.name.charAt(0).toUpperCase() + item.name.slice(1),
detailsUrl: item.url,
};
add(pokemon);
});
})
.catch(function(error) {
console.error(error);
});
}
function loadDetails(item) {
let url = item.detailsUrl;
return fetch(url)
.then(function(response) {
return response.json();
})
.then(function(details) {
item.imageUrlFront = details.sprites.front_default;
item.imageUrlBack = details.sprites.back_default;
item.id = details.id;
item.height = details.height;
item.weight = details.weight;
item.types = details.types;
item.abilities = details.abilities;
})
.catch(function(error) {
console.error(error);
});
}
return {
add: add,
getAll: getAll,
addListItem: addListItem,
search: search,
showDetails: showDetails,
loadList: loadList,
loadDetails: loadDetails,
buttonEvent: buttonEvent,
};
})();
pokemonRepository.loadList().then(function() {
pokemonRepository.getAll().forEach(function(pokemon) {
pokemonRepository.addListItem(pokemon);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="The Pokédex is a simple encyclopedia of Pokémon and their characteristics." />
<link rel="shortcut icon" href="img/favicon.png" type="image/x-icon" />
<title>Pokédex App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.3/font/bootstrap-icons.css" />
<link rel="stylesheet" href="/dist/style.production.css" />
</head>
<body>
<nav class="navbar navbar-expand-lg sticky-top navbar-light bg-light">
<div class="container-fluid">
<a href="#home" class="navbar-brand">
<img src="img/ball.png" width="30" height="24" alt="" class="d-inline-block align-text-top" /><span class="text-uppercase font-weight-bold text-secondary">Pokèdex</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#home">Home</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
</ul>
</li>
</ul>
<form class="d-flex row" role="search">
<!-- <input
class="form-control me-2"
placeholder="Pokemon Name"
aria-label="Search"
/> -->
<button class="btn btn-outline-secondary" type="submit">
<i class="bi bi-search"></i>
</button>
</form>
</div>
</div>
</nav>
<p class="fw-bold position-absolute top-10 start-50 text-center text-danger"></p>
<!-- Pokemon Display -->
<div class="container">
<ul class="list-group list-group-horizontal flex-fill row mt-4"></ul>
</div>
<!-- Display Ends Here -->
<div class="modal fade" id="pokemonModal" tabindex="-1" role="dialog" aria-labelledby="pokemonModalLabel" aria-hidden="true">
<div class="modal-dialog pt-5 text-center" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title col-sm-3" id="pokemonModalLabel"></h5>
<button type="button" class="btn-close me-3" data-dismiss="modal" aria-label="Close" aria-hidden="true"></button>
</div>
<!-- Content is dynamically created using jquery -->
<div class="modal-body"></div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
<script src="/src/js/scripts.js"></script>
<script src="/src/js/promise-polyfill.js"></script>
<script src="/src/js/fetch-pollyfill.js"></script>
</body>
</html>
Since searchQuery is a jQuery object, you need to use its .val() method to set and get the value. So change.
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
to
searchQuery.val((i, value) => value[0].toUpperCase() + value.slice(1));
I want to add an event to the "Important" link i.e. When One user clicks the "Important" link, the corresponding card color should be changed and saved in the localstorage but, when I am accessing that DOM file which I passed as a string, I am unable to do it. For e.g. - I can't access to document.getElementsByClassName("noteCard") in function markNotes(index). But at the same time
console.log("Color is not applied") executes successfully. If I am adding document.body.style.backgroundColor = "lightblue"; then also body color changes accordingly, but the I want to change the background color of the card with class "noteCard" only. I am really stuck with it.
Below is my HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Magic Notes</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="Customstyle.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
<a class="navbar-brand" href="#">Magic Notes</a>
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://www.facebook.com/balabhadra.chand/" target="_blank">About me</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTitle" type="search" placeholder="Search by title" aria-label="Search">
</form>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search text" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0 " id="searchBtn" type="submit">Search</button>
</form>
</div>
</nav>
<h1 class="heading">It's all about magic !!!</h1>
<div class="card" style="width: 1000px;">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Add a title to your note</textarea></span>
</div>
<textarea class="form-control" id="addTitle" aria-label="With textarea"></textarea>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="exampleFormControlTextarea1">Write your Note</label>
<textarea class="form-control" id="addTxt" rows="3"></textarea>
</div>
</form>
<button class="btn btn-primary" id="addBtn">ADD NOTE</button>
</div>
</div>
<hr>
<h5>Your Notes</h5>
<hr>
<div id="notes" class="row container-fluid"></div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script src="myscript.js"></script>
</body>
Here is my JavaScript code
console.log('MagicNotes')
showNotes();
let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function(e) {
let addTxt = document.getElementById("addTxt");
let addTitle = document.getElementById("addTitle");
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
let myObj = {
title: addTitle.value,
text: addTxt.value
}
notesObj.push(myObj)
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
addTitle.value = "";
showNotes();
});
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
let html = "";
notesObj.forEach(function(element, index) {
html += `<div class="noteCard card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
Important
</div>
</div>`;
});
let notesElem = document.getElementById("notes");
if (notesObj.length != 0) {
notesElem.innerHTML = html;
} else {
notesElem.innerHTML = `Please add a note by clicking "ADD NOTE"`;
}
}
function deleteNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
function markNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
document.getElementsByClassName("noteCard").style.color = "lightblue";
console.log("Color is not applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
let searchText = document.getElementById('searchTxt');
searchText.addEventListener("input", function(txt) {
let inputVal = searchText.value.toLowerCase();
// console.log('Input event fired!', inputVal);
let noteCards = document.getElementsByClassName('noteCard');
Array.from(noteCards).forEach(function(element) {
let cardTxt = element.getElementsByTagName("p")[0].innerText;
if (cardTxt.includes(inputVal)) {
element.style.display = "block";
} else {
element.style.display = "none";
}
// console.log(cardTxt);
})
})
let searchTitle = document.getElementById('searchTitle');
searchTitle.addEventListener("input", function(title) {
let inputValTitle = searchTitle.value.toLowerCase();
let noteCardsTitle = document.getElementsByClassName('noteCard');
Array.from(noteCardsTitle).forEach(function(element) {
let cardTitle = element.getElementsByTagName("h5")[0].innerText;
if (cardTitle.includes(inputValTitle)) {
element.style.display = "block";
} else {
element.style.display = "none";
}
// console.log(cardTitle);
})
})
You were missing index while fetching element inside markNotes:
function markNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
let noteCard = document.getElementsByClassName("noteCard")[index];
noteCard.style.color = "lightblue";
console.log("Color is applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
//showNotes(); you don't need to add this again
}
complete working code fiddle link
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.
$(document).ready(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
getMovies(searchText);
e.preventDefault();
});
});
function getMovies(searchText) {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
.then((response) => {
console.log(response);
let movies = response.data.Search;
let output = '';
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.poster_path}">
<h5>${movie.original_title}</h5>
<a onclick="https://www.themoviedb.org/movie/('${movie.id}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('id', id);
window.location = 'movie.html';
return false;
}
function getMovie() {
let id = sessionStorage.getItem('id');
axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
.then((response) => {
console.log(response);
let movie = response.data;
let output = `
<div class="row">
<div class="col-md-4">
<img src="${movie.Poster}" class="thumbnail">
</div>
<div class="col-md-8">
<h2>${movie.Title}</h2>
<ul class="list-group">
<li class="list-group-item"><strong>Genre:</strong> ${movie.genres.Name}</li>
<li class="list-group-item"><strong>Released:</strong> ${movie.release_date}</li>
<li class="list-group-item"><strong>Rated:</strong> ${movie.vote_average}</li>
<li class="list-group-item"><strong>Review:</strong> ${movie.overview}</li>
</ul>
</div>
</div>
<div class="row">
<div class="well">
<h3>Plot</h3>
${movie.Plot}
<hr>
View TMDb
Go Back To Search
</div>
</div>
`;
$('#movie').html(output);
})
.catch((err) => {
console.log(err);
});
}
#movies img,
#movie img {
width: 100%;
}
#media(min-width:960px) {
#movies .col-md-3 .well {
height: 390px;
}
#movies .col-md-3 img {
height: 240px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MovieInfo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
--More details, because I have more code:
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
This will help you click here, Now it is working. There was very small bug, which I mentioned to you.
And also fixed the image not showing issue.
Just replace response.data.Search by response.data.results
$(document).ready(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
getMovies(searchText);
e.preventDefault();
});
});
function getMovies(searchText) {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
.then((response) => {
console.log(response);
let movies = response.data.results;
let output = '';
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.poster_path}">
<h5>${movie.original_title}</h5>
<a onclick="https://www.themoviedb.org/movie/('${movie.id}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('id', id);
window.location = 'movie.html';
return false;
}
function getMovie() {
let id = sessionStorage.getItem('id');
axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
.then((response) => {
console.log(response);
let movie = response.data;
let output = `
<div class="row">
<div class="col-md-4">
<img src="${movie.Poster}" class="thumbnail">
</div>
<div class="col-md-8">
<h2>${movie.Title}</h2>
<ul class="list-group">
<li class="list-group-item"><strong>Genre:</strong> ${movie.genres.Name}</li>
<li class="list-group-item"><strong>Released:</strong> ${movie.release_date}</li>
<li class="list-group-item"><strong>Rated:</strong> ${movie.vote_average}</li>
<li class="list-group-item"><strong>Review:</strong> ${movie.overview}</li>
</ul>
</div>
</div>
<div class="row">
<div class="well">
<h3>Plot</h3>
${movie.Plot}
<hr>
View TMDb
Go Back To Search
</div>
</div>
`;
$('#movie').html(output);
})
.catch((err) => {
console.log(err);
});
}
#movies img,
#movie img {
width: 100%;
}
#media(min-width:960px) {
#movies .col-md-3 .well {
height: 390px;
}
#movies .col-md-3 img {
height: 240px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MovieInfo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
So I am developing this app in which i want to apply pagination to list of templates.
template objects are stored in the list.
I am displaying thumbnails of templates on the page and I want to apply pagination for this page.
So far I have tried following solution but it didn't work.
It displaying the pagination correctly but when I click on the link its not updating the contents of the page.
list.html
<div class="container">
<div class="homepage-header">
<h2 class="homepage-title text-center wow fadeInDown animated" style="visibility: visible; animation-name: fadeInDown; -webkit-animation-name: fadeInDown;"> TEMPLATES </h2>
</div>
<div class="row">
<div class="col-md-6 col-sm-6" style="text-align: left">
<div class="form-inline">
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="searchParam" ng-model-options="{ debounce: 400 }" placeholder="Search template ..."
/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="searchParam = '';
retreivePageData(0);" ng-show="searchParam" style="pointer-events: auto; "></a>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6" style="text-align: right; vertical-align: middle; padding-right: 30px;">
<div class="form-inline">
{{selectedOption}}
<i class="fa fa-toggle-on fa-2x active" ng-if="status == true" ng-click="changeStatus();" title="Show component based templates"></i>
<i class="fa fa-toggle-on fa-2x fa-rotate-180 inactive" ng-if="status == false" ng-click="changeStatus();" title="Show image based templates"></i>
<button ng-click="newTemplateConfig()" class="btn btn-primary btn-xs" title="Add new template"><i class="fa fa-plus-circle fa-fw"></i>New Template</button>
</div>
</div>
</div>
<div class="homepage-ui-showcase-2-css row wow zoomIn animated" style="height: 402px;padding: 5px 0px; visibility: visible; animation-name: zoomIn; -webkit-animation-name: zoomIn;">
<div ng-repeat="(templateIndex, templateModel) in templatesList | filter:searchParam | limitTo: itemsPerPage">
<div class="active col-md-3 col-lg-3 col-sm-6 col-xs-12 mix design painting" style="display: inline-block;padding-top: 10px;"
ng-init="visible=false" ng-mouseover="visible=true" ng-mouseleave="visible=false">
<div class="portfolio-item shadow-effect-1 boxShadow" style="max-width: 250px;padding:0.3px;border:2px dotted #bebede;cursor: pointer">
<div class="mainBadge">
<kbd>{{templateModel.badge}}</kbd>
</div>
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="false" style="height: 130px;" ui-sref="/designer/:pageId({pageId:templateModel.id})" class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-puzzle-piece fa-4x"></i>
</div>
<div ng-switch-when="true" style="height: 130px;" ui-sref="annotator/:annotatedTemplateId({annotatedTemplateId:templateModel.id})"
class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-file-image-o fa-4x"></i>
</div>
</div>
<div class="portfolio-item-content" title="{{templateModel.name}}">
<h3 class="header" style="font-size: 13px;text-align: center;display:inline;">
{{templateModel.name}}
</h3>
<small class="pull-right" ng-show="visible" style="display: inline; padding-top: 4px">
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="true" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'A',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
<div ng-switch-when="false" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'T',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
</div>
</small>
</div>
</div>
</div>
</div>
</div>
<div class="row " style="margin-top: 10px; padding-top:0px;">
<div class="pagination-div pull-right" style="">
<!--<pagination class="pull-right" total-items="templatesList.length" ng-model="currentPage" max-size="maxSize" items-per-page="itemsPerPage"></pagination> -->
<uib-pagination total-items="templatesList.length" ng-model="currentPage" ng-change="pageChanged()" max-size="maxSize" class="pagination-sm" items-per-page="itemsPerPage" boundary-link-numbers="true"></uib-pagination>
</div>
</div>
</div>
list.controller.js
'use strict';
angular.module('rapid').controller('HomeListController',
function($scope, $rootScope, $window, $modal, ServiceFactory, toaster, ReadFileService, AnnotationService, AnnotateService, DocumentService) {
$scope.templatesList = [];
$scope.selectedOption = 'All';
$scope.annotateTemplateMeta = [];
$scope.rapidTemplateMeta = [];
$scope.maxSize = 5;
$scope.init = function() {
$scope.status = true;
$scope.selectedOption = "Image Based";
$scope.retrieveTemplates($scope.status);
$scope.currentPage = 1;
};
$scope.changeStatus = function(){
$scope.status = !$scope.status;
$scope.retrieveTemplates($scope.status);
};
$scope.retrieveTemplates = function(selectedOption) {
$scope.templatesList = [];
if(selectedOption) {
$scope.selectedOption = "Image Based";
$scope.fetchAnnotationTemplates("Annotate");
} else {
$scope.selectedOption = "Component Based";
$scope.fetchRapidTemplates("Rapid");
}
};
$scope.fetchAnnotationTemplates = function(selectedOption) {
AnnotateService.get().$promise.then(function(result) {
$scope.annotateTemplateMeta = result[0];
console.log('Annotated template count :: ' + result[0].length);
if (selectedOption === 'All') {
$scope.fetchRapidTemplates(selectedOption);
} else {
$scope.prepareTemplateList(selectedOption);
}
});
};
$scope.fetchRapidTemplates = function(selectedOption) {
ServiceFactory.PagesService.getAllPages().$promise.then(function(result) {
$scope.rapidTemplateMeta = result[0];
console.log('Rapid template count :: ' + result[0].length);
$scope.prepareTemplateList(selectedOption);
});
};
$scope.prepareTemplateList = function(selectedOption) {
$scope.itemsPerPage = 1;
var getPaginatedTemplateList = 'getList';
$scope.currentPage = 0;
if (selectedOption === 'Annotate') {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity:annotate.dynamic_entity, badge:"Image Based" };
$scope.templatesList.push(templateObject);
});
} else if (selectedOption === 'Rapid') {
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity:rapidTemplate.pageObj.entity, badge:"Component Based" };
$scope.templatesList.push(templateObject);
});
//alert('Rapid count '+selectedOption + $rootScope.rapidTemplateMeta.length);
} else {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity:annotate.dynamic_entity, badge:"Image Based" };
$scope.templatesList.push(templateObject);
});
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity:rapidTemplate.pageObj.entity, badge:"Component Based" };
$scope.templatesList.push(templateObject);
});
$scope.totalItems = $scope.templatesList.length;
$scope.maxSize = 5;
}
//$scope.retreivePageData(0);
};
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
alert('Page changed to: ' + $scope.currentPage);
});
};
$scope.newTemplateConfig = function (size) {
var modalInstance = $modal.open({
backdrop: 'static',
keyboard: false,
animation: $scope.animationsEnabled,
templateUrl: 'scripts/app/home/modal/template.modal.html',
controller: 'TemplateModalCtrl',
size: size,
resolve: {templateModel: function () {
return null;
},
title: function () {
return 'Create New Template';
},
templateType: function() {
if($scope.status) {
return 'Annotate';
} else {
return 'Rapid'
}
}
}
});
modalInstance.result.then(function (saveAnnotatedTemplateConfig) {
alert('modal result')
//$scope.saveAnnotatedTemplateConfig(saveAnnotatedTemplateConfig.templateConfigModel);
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
$scope.init();
});
Is there anything wrong with my code?
Please provide some inputs on this.
You can use ui-grid directive to solve your pagination problem.
Please refer to the ui-grid API.
Checkout these 2 plunkers :
Plunker 1
Plunker 2
app.js
$scope.add = function () {
$('#btn').click(function() {
// insert a SPAN tag with class="spn" at the end in all DIVs with class="cls"
$scope.data=[];
var add=' <input type="text" name="currency" id="autocomplete">' ;
$('div.cls').append(add);
i++;
$scope.count++;
});
}
$scope.autocomplete=function(){
var currencies = [
{ value: 'Afghan afghani' },
{ value: 'Albanian lek'},
{ value: 'Algerian dinar'},
{ value: 'European euro' }
];
// setup autocomplete function pulling from currencies[] array
$('#autocomplete').autocomplete({
lookup: currencies,
});
}
html
<div class="cls" id="idd"></div>
<button type="button" class="btn btn-default btn-sm" id="btn">
<span class="glyphicon glyphicon-plus"></span> Add
</button>
This auto complete function run without using as append.. but when i used it after appending text field like above it does not works.can anyone help me.
This sample show to you how can create autocomplete using Angular, without jQuery autocomplete.
var app = angular.module("app", []);
app.controller("ctrl", function ($scope, $filter) {
$scope.suggestions = [];
$scope.selectedData = [];
$scope.defaultData = [
{ value: "Afghan afghani" },
{ value: "Albanian lek" },
{ value: "Algerian dinar" },
{ value: "European euro" }
];
$scope.search = function () {
var length = $scope.autocomplete.length;
if (length === 0) {
$scope.suggestionsNotFound = false;
$scope.suggestions = [];
} else {
var result = $filter("filter")($scope.defaultData, { value: $scope.autocomplete });
$scope.suggestions = result;
$scope.suggestionsNotFound = false;
if (result.length === 0) {
$scope.suggestionsNotFound = true;
}
}
///select
$scope.select = function (item) {
var isExist = $filter("filter")($scope.selectedData, { value: item.value }, true)[0];
if (!isExist) {
$scope.selectedData.push(item);
$scope.autocomplete = null;
$scope.suggestions = [];
}
}
///remove
$scope.remove = function (index) {
$scope.selectedData.splice(index, 1);
}
}
});
.autocomplete span {
margin-left: 5px;
}
.autocomplete span i {
color: red;
cursor: pointer;
}
<!doctype html>
<html ng-app="app" ng-controller="ctrl">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="autocomplete">
<input class="form-control" type="text" ng-model="autocomplete" ng-change="search()" />
<div class="clearfix"></div>
<span class="label label-default" ng-repeat="data in selectedData">
{{data.value}}
<i ng-click="remove($index)" class="glyphicon glyphicon-remove"></i>
</span>
<ul class="list-group">
<li class="list-group-item" ng-repeat="suggestion in suggestions" ng-click="select(suggestion)">
{{suggestion.value}}
</li>
</ul>
<div class="alert alert-info" ng-if="suggestionsNotFound">
<b>[{{autocomplete}}] not found!</b>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>