Text not changing after `button--reset` pressed - javascript

Problem
I can select a player by clicking btn--add, but when I click btn--reset to reset my picks and then try to add players again, the text in the list of spans does not change to reflect the player of the last name clicked.
Update #1: Yes, I'm calling both functions at the bottom of scripts.js (it is just not shown in the code snippet)
scripts.js
function countPlayers(){
var playerName = null;
var player = null;
var pickedF = null;
var pickedD = null;
var pickedG = null;
$(".player").click(function(){
// Select the current player
player = $(this);
// Count number of players of each position that have been clicked
pickedF = $(".player--forward.is-selected").length;
pickedD = $(".player--defenseman.is-selected").length;
pickedG = $(".player--goalie.is-selected").length;
// Grab the name of the player last clicked
playerName = player.find(".player__name").text();
// Use regex to replace spaces with hypens and then lowercase the text
// window.location.hash will append #playerName onto the URL
var playerNameHypenate = playerName.replace(/\s+/g, '-').toLowerCase();
window.location.hash = playerNameHypenate;
});
$(".btn--add").click(function(){
// Ensures names don't match
var playerExists = $('.player__pick:contains("'+playerName+'")').length;
// Changes the opacity of a picked player to 0.5
player.addClass("is-selected");
if (player.hasClass("player--forward")) {
if (!playerExists) {
$(".player__pick--forward.is-empty").eq(0).html(playerName);
$(".player__pick--forward.is-empty").eq(0).removeClass("is-empty");
if (pickedF < 2) {
pickedF++;
}
console.log(pickedF);
if (pickedF === 2) {
$(".player--forward").not(".is-selected").css("pointer-events", "none");
console.log("Locked forwards");
} else {
$(".player--forward").css("pointer-events", "auto");
}
}
}
if (player.hasClass("player--defenseman")) {
if (!playerExists) {
$(".player__pick--defenseman.is-empty").eq(0).html(playerName);
$(".player__pick--defenseman.is-empty").eq(0).removeClass("is-empty");
if (pickedD < 3) {
pickedD++;
}
console.log(pickedD);
if (pickedD === 3) {
$(".player--defenseman").not(".is-selected").css("pointer-events", "none");
console.log("Locked defensemen");
} else {
$(".player--defenseman").css("pointer-events", "auto");
}
}
}
if (player.hasClass("player--goalie")) {
if (!playerExists) {
$(".player__pick--goalie.is-empty").eq(0).html(playerName);
$(".player__pick--goalie.is-empty").eq(0).removeClass("is-empty");
if (pickedG < 1){
pickedG++;
}
console.log(pickedG);
if (pickedG === 1) {
$(".player--goalie").not(".is-selected").css("pointer-events", "none");
console.log("Locked goalie");
} else {
$(".player--goalie").css("pointer-events", "auto");
}
}
}
});
$(".btn--remove").click(function(){
player.removeClass("is-selected");
// This refers to each element with a class of `player__pick--forward`
// Then we are seeing if this element in the `player__pick--forward` array matches
if (player.hasClass("player--forward")) {
$(".player__pick--forward").each(function(index) {
if ( $(this).text() === playerName ) {
pickedF--;
$(this).html("Pick a Forward");
$(this).addClass("is-empty");
console.log(pickedF);
}
})
}
if (player.hasClass("player--defenseman")) {
$(".player__pick--defenseman").each(function(index) {
if ( $(this).text() === playerName ) {
pickedD--;
$(this).html("Pick a Defenseman");
$(this).addClass("is-empty");
console.log(pickedD);
}
})
}
if (player.hasClass("player--goalie")) {
$(".player__pick--goalie").each(function(index) {
if ( $(this).text() === playerName ) {
pickedG--;
$(this).html("Pick a Goalie");
$(this).addClass("is-empty");
console.log(pickedG);
}
})
}
});
}
// // Clear all picks
function clearPicks() {
$(".btn--reset").click(function(){
// Deselect players
$(".player").removeClass("is-selected");
// Change pointer events back to auto
$(".player").css("pointer-events", "auto");
// Revert text back to defaults
$(".player__pick--forward").html("Pick a Forward");
$(".player__pick--defenseman").html("Pick a Defenseman");
$(".player__pick--goalie").html("Pick a Goalie");
pickedF = 0;
pickedD = 0;
pickedG = 0;
console.log(pickedF, pickedD, pickedG);
});
}
index.html
<div class="popup clearfix">
<div class="icon-container">
<i class="fa fa-times" aria-hidden="true"></i>
</div>
<img src="" alt="" class="popup__picture animated">
<div class="popup__text">
<p class="popup__position">tk-position</p>
<p class="popup__name">tk-name</p>
<p class="popup__years">tk-years</p>
<p class="popup__description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi ad dicta sunt unde, sed quae nihil inventore voluptates nulla voluptate laudantium nesciunt quo, aspernatur deleniti quod harum, nisi error doloribus.</p>
<div class="popup__stats">
<p>tk-stats</p>
</div>
<div class="buttons">
<button class="btn--add">Add to team</button>
<button class="btn--remove">Remove from team</button>
</div>
</div>
</div>
<ul class="">
<li><span class="player__pick player__pick--forward is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a forward</span></li>
<li><span class="player__pick player__pick--forward is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a forward</span></li>
<li><span class="player__pick player__pick--defenseman is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a defenseman</span></li>
<li><span class="player__pick player__pick--defenseman is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a defenseman</span></li>
<li><span class="player__pick player__pick--defenseman is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a defenseman</span></li>
<li><span class="player__pick player__pick--goalie is-empty"><i class="fa fa-long-arrow-right" aria-hidden="true"></i> Pick a goalie</span></li>
</ul>
<button class="btn--reset">Clear all picks</button>

All of you click event binding functions are nested inside the functions countPlayers and clearPicks. Those functions are never called so the click events are never attached to the DOM.

Related

Toggle span text with i tag

How can i make my code above change the span text without removing the 'i' tag?
function toggle(e) {
let txt = e.innerText;
e.innerText = txt == 'Modo escuro' ? 'Modo claro' : 'Modo escuro';
}
<a onclick="toggle(this)" id="theme-toggle" href="#" class="nav__link" >
<i class='bx bx-bulb nav__icon' ></i>
<span class="nav__name">Modo escuro</span>
</a>
live demo here: https://pauletatv.netlify.app
Includes it
Just add your tags into your .innerHTML element.
let modo = 0;
function toggle(e) {
if (modo == 0) {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo claro</span>";
modo = 1;
} else {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo escuro</span>";
modo = 0;
}
}
<a onclick="toggle(this)" id="theme-toggle" href="#" class="nav__link" >Click</a>
In alternative
You can check user theme preference cookies, in this way:
let modo = 0;
if (document.cookie.indexOf("theme=1") !== -1) {
modo = 1;
}
function toggle(e) {
if (modo == 0) {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo claro</span>";
modo = 1;
} else {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo escuro</span>";
modo = 0;
}
}
<a onclick="toggle(this)" id="theme-toggle" href="#" class="nav__link" >Click</a>

jQuery Remember toggleClass status in list

I have a function:
function toggle(event) {
$(`#${event.target.id}`).toggleClass('fa-power-on fa-power-off');
}
I also have a list of buttons:
<i id="id1" onclick="toggle($event)"></i>
<i id="id14" onclick="toggle($event)"></i>
<i id="id12" onclick="toggle($event)"></i>
<i id="id17" onclick="toggle($event)"></i>
<i id="id18" onclick="toggle($event)"></i>
<i id="id1w" onclick="toggle($event)"></i>
I need the status of the toggleClass icon to be remembered for each.
Either by localStorage or id's and status all in an object and then saved on localstorage or other.
The <i></i> list is dynamic so I cannot hardcode it.
How can I do this?
Consider the following example.
$(function() {
function toggle(el) {
$(el).toggleClass("fa-power-on fa-power-off");
}
function getPowerStatus(selector) {
var results = [];
$(selector).each(function(i, el) {
var key = $(el).attr("id");
var val = $(el).hasClass("fa-power-on");
var item = {};
item[key] = val;
results.push(item);
});
return results;
}
function saveStatus(stats) {
localStorage.setItem("status", JSON.stringify(stats));
}
function getStatus() {
return JOSN.parse(localstorage.getItem("status"));
}
$("i[id^='id']").click(function(e) {
toggle(this);
var status = getPowerStatus("i[id^='id']");
console.log(status);
saveStatus(status);
});
});
.fa-power-off {}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i id="id1" class="fas fa-power-off"></i>
<i id="id14" class="fas fa-power-off"></i>
<i id="id12" class="fas fa-power-off"></i>
<i id="id17" class="fas fa-power-off"></i>
<i id="id18" class="fas fa-power-off"></i>
<i id="id1w" class="fas fa-power-off"></i>
This created functions to toggle, gather the status of each, set, and get those status to Local Storage.
Not sure what Icon Set you're using, but Font-Awesome does not have a fa-power-on. Which would mean you'd want to toggle a different class.
$(function() {
function toggle(el) {
$(el).toggleClass("on");
}
function getPowerStatus(selector) {
var results = [];
$(selector).each(function(i, el) {
var key = $(el).attr("id");
var val = $(el).hasClass("on");
var item = {};
item[key] = val;
results.push(item);
});
return results;
}
function saveStatus(stats) {
localStorage.setItem("status", JSON.stringify(stats));
}
function getStatus() {
return JOSN.parse(localstorage.getItem("status"));
}
$("i[id^='id']").click(function(e) {
toggle(this);
var status = getPowerStatus("i[id^='id']");
console.log(status);
saveStatus(status);
});
});
.fa-power-off {
border-radius: 50%;
}
.fa-power-off.on {
background: black;
color: white;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i id="id1" class="fas fa-power-off"></i>
<i id="id14" class="fas fa-power-off"></i>
<i id="id12" class="fas fa-power-off"></i>
<i id="id17" class="fas fa-power-off"></i>
<i id="id18" class="fas fa-power-off"></i>
<i id="id1w" class="fas fa-power-off"></i>
Now you can Click them on or off. Each time click event happens, it toggle the class and updates the saved status. You can then get the status when the page loads and re-apply the on class as needed.

function doesnt work, add to favorites E-commerce project

what I need to do is when I click on the heartBtn it turns red and add the item to an array of objects in the localstorage productsInFavArr and when I click again it should turns grey and remove the object from productsInFavArr.
the adding function is working perfectly in added the item to the arr part but the drawProductUI function supposed to check if the product exist in the productsInFacArr the btn will be red and if not its gonna be grey, so i put the drawProductUIfunction in the adding and removing function after adding and removing the item but it doesnt work till I reload the page
and the removing function remove the object from the arr after two click and still doesnt change colot of the btn
so my main problem is changing the color of the btn after adding or removing the item and the removing function remove the item after two clicks
here is the code:
// Draw Product UI
function drawProductUI(array){
var productsUI = array.map((item) => {
if (productsInFavArr) {
for (const favProd of productsInFavArr){
if (favProd.id === item.id) {
// console.log(favProd);
return `
<div class="product-item">
<div class="product-img-container">
<img src=${item.imgURL} alt="products" class="product-img" width="100%" height="150px">
</div>
<div class="product-text">
<h2 class="product-title">${item.title}</h2>
<span class="product-desc">${item.desc}</span>
<p class="product-price">USD ${item.price}</p>
</div>
<div class="product-btns">
<button class="add-to-cart">Add To Cart</button>
<button class="heart-btn heart-icon-red" onclick="removeItemFromFav( ${item.id} )"><i class="far fa-heart"></i></button>
</div>
</div>
`;
}
}}
return`
<div class="product-item">
<div class="product-img-container">
<img src=${item.imgURL} alt="products" class="product-img" width="100%" height="150px">
</div>
<div class="product-text">
<h2 class="product-title">${item.title}</h2>
<span class="product-desc">${item.desc}</span>
<p class="product-price">USD ${item.price}</p>
</div>
<div class="product-btns">
<button class="add-to-cart">Add To Cart</button>
<button class="heart-btn heart-icon" ><i class="far fa-heart"></i></button>
</div>
</div>
`
});
productsContainer.innerHTML = productsUI.join("");
}
drawProductUI(allProducts)
// add to favorites
for(let f=0; f < heartBtn.length; f++){
heartBtn[f].addEventListener("click" ,()=>{
addToFavorites(allProducts[f]);
function addToFavorites(product){
if (localStorage.getItem("userValidate") && localStorage.getItem("passValidate")) {
let productsInFavObj = localStorage.getItem("productsInFavObj");
productsInFavObj = JSON.parse(productsInFavObj);
if(productsInFavObj != null){
if(productsInFavObj[product.id] == undefined){
productsInFavObj = {
...productsInFavObj,
[product.id] : product
}
}
}else{
productsInFavObj = {
[product.id] : product
}
}
let productsInFavArr = Object.values(productsInFavObj)
localStorage.setItem("productsInFavArr" , JSON.stringify(productsInFavArr) )
localStorage.setItem("productsInFavObj" , JSON.stringify(productsInFavObj) )
}else{
window.location.href = "login.html";
}
}
drawProductUI(allProducts)
})
}
// Remove From Favorite
function removeItemFromFav(id){
for(let f=0; f < heartBtn.length; f++){
let productsInFavArr = localStorage.getItem("productsInFavArr")
if(productsInFavArr){
let items = JSON.parse(productsInFavArr);
console.log("removed item:",allProducts[f]);
let filteredItems = items.filter((item) => item.id !== id);
localStorage.setItem("productsInFavArr" , JSON.stringify(filteredItems));
localStorage.setItem("productsInFavObj" , JSON.stringify(filteredItems) )
drawProductUI(allProducts)
console.log(filteredItems);
if(filteredItems.length==0){
localStorage.removeItem("productsInFavArr")
localStorage.removeItem("productsInFavObj")
}
}
}
}
and here is an example of the products
let products = [
{
title: "Sunglasses",
imgURL: "images/Products/sunglasses.jpg",
desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
price:80,
id: 1
},
{
title: "Laptop",
imgURL: "images/Products/laptop.jpg",
desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
price:100,
id: 2
},
{
title: "Microphone",
imgURL: "images/Products/mic.jpg",
desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
price:75,
id: 3
},
{
title: "Cat",
imgURL: "images/Products/cat.jpg",
desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
price:200,
id: 4
},
]
thanks
In the drawProductUI function you are not reading local storage value, but it depends on productsInFavArr which is probably only reading the local storage value ONCE. I think you need to grab the fresh value whenever you call drawProductUI in order to reflect changes made to local storage without reloading the page.
function drawProductUI(array){
let productsInFavArr = JSON.parse(localStorage.getItem("productsInFavArr")) || []; // read the value here so it's fresh before redraw happens
var productsUI = array.map((item) => {
// rest of the function code
In the drawProductUI function you define handler for selected items:
<button class="heart-btn heart-icon-red" onclick="removeItemFromFav(${item.id})">
<i class="far fa-heart"></i>
</button>
You should do the same for the unselected button version:
<button class="heart-btn heart-icon" onclick="addToFavorites(${item.id})">
<i class="far fa-heart"></i>
</button>
this way the click handler will be attached every time you redraw the UI not only once when the js file is being read, which is the case when you define the handler as you currently do.
Having this in place you need to define the addToFavorites function at the top level, so outside of the loop, just as you define removeItemFromFav.
Since the handler takes id of the product now, you need to find the appropriate product before processing it.
You also want to redraw the UI when this is clicked so add the appropriate method to the bottom of the function.
I've attached comments indicating those changes:
function addToFavorites(id){ // this is now defined at the top level as removeItemFromFav
if (localStorage.getItem("userValidate") && localStorage.getItem("passValidate")) {
const product = allProducts.find(p => p.id == id); // this and next lines handle product lookup
if (!product) { return; }
let productsInFavObj = localStorage.getItem("productsInFavObj");
productsInFavObj = JSON.parse(productsInFavObj);
if(productsInFavObj != null){
if(productsInFavObj[id] == undefined){
productsInFavObj = {
...productsInFavObj,
[id] : product
}
}
}else{
productsInFavObj = {
[id] : product
}
}
let productsInFavArr = Object.values(productsInFavObj)
localStorage.setItem("productsInFavArr" , JSON.stringify(productsInFavArr) )
localStorage.setItem("productsInFavObj" , JSON.stringify(productsInFavObj) )
drawProductUI(allProducts); // this redraws the UI
}else{
window.location.href = "login.html";
}
}
Last thing you want to correct is the removeItemFromFav function.
Loop is unnecessary
function removeItemFromFav(id){
// loop is gone now, also console.logs are gone
let productsInFavArr = localStorage.getItem("productsInFavArr")
if(productsInFavArr){
let items = JSON.parse(productsInFavArr);
let filteredItems = items.filter((item) => item.id !== id);
localStorage.setItem("productsInFavArr" , JSON.stringify(filteredItems));
localStorage.setItem("productsInFavObj" , JSON.stringify(filteredItems) )
drawProductUI(allProducts)
if(filteredItems.length==0){
localStorage.removeItem("productsInFavArr")
localStorage.removeItem("productsInFavObj")
}
}
}

jQuery add class to nearest element

I tried with .next(), .closest() .parent() but non of them worked.
Here is my html markup:
<div id="arrownav1" class="ct_as_arrow_nav ">
<div class="ct_amy_arrows_next">
<i class="fa fa-angle-right next-arrow"></i>
</div>
<div class="ct_amy_arrows_prev">
<i class="fa fa-angle-left prev-arrow"></i>
</div>
</div>
I am trying to show left arrow after user does the first click on the right arrow.
I hide it with:
jQuery('.ct_amy_arrows_prev').removeClass("prev_show");
Then I show it with:
jQuery('.ct_amy_arrows_prev').addClass("prev_show");
It works but since there are multiple instances of that slider on a page click on the first slider activates all left arrows on all sliders.
So I need a way to just activate that closest element and add prev_show class to it.
What am I doing wrong?
The whole nav code:
//Navigation
//==================================================
function initButtons() {
jQuery('#arrownav' + sliderID + ' .next-arrow').click(function() {
gonext();
});
jQuery('#arrownav' + sliderID + ' .prev-arrow').click(function() {
goprev();
});
}
var stopnextslide = 0;
function gonext() {
var stopnextslide = 0;
var n = jQuery('#ct_as_amy_sliderid' + sliderID + ' ct_amy_section').length;
jQuery('#ct_as_amy_sliderid' + sliderID + ' ct_amy_section').each(function() {
if (jQuery(this).hasClass('bespoke-active') && Number(jQuery(this).attr('rel')) + 3 == n) {
deck.slide(0);
stopnextslide = 1;
}
});
if (stopnextslide != 1) {
jQuery(this).closest(".ct_as_arrow_nav").find(".ct_amy_arrows_prev").addClass("prev_show");
deck.next();
}
};
function goprev() {
var stopnextslide = 0;
var n = jQuery('#ct_as_amy_sliderid' + sliderID + ' ct_amy_section').length;
jQuery('#ct_as_amy_sliderid' + sliderID + ' ct_amy_section').each(function() {
if (jQuery(this).hasClass('bespoke-active') && Number(jQuery(this).attr('rel')) == 3) {
deck.slide(n - 1);
stopnextslide = 1;
}
if (jQuery(this).hasClass('bespoke-active') && Number(jQuery(this).attr('rel')) == 1) {
}
});
if (stopnextslide != 1) {
deck.prev();
}
};
Thanks
You know the structure. Just navigate up to the parent then search for the previous button. No need to use expensive operations like closest
$('.ct_amy_arrows_next').on('click', function() {
$(this).parent().find('.ct_amy_arrows_prev').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="arrownav1" class="ct_as_arrow_nav ">
<div class="ct_amy_arrows_next">
<i class="fa fa-angle-right next-arrow">></i>
</div>
<div class="ct_amy_arrows_prev" style="display: none;">
<i class="fa fa-angle-left prev-arrow"><</i>
</div>
</div>
You can achieve this using closest and find methods:
$('.next-row').click(function(){
$(this).closest('.ct_as_arrow_nav').find('.ct_amy_arrows_prev').addClass("prev_show");
});
$('.next-arrow').click(function(){
$(this).closest('.ct_as_arrow_nav').find('.ct_amy_arrows_prev').addClass("prev_show");
});
.prev_show{
color:red;
}
i{
font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>
<div id="arrownav1" class="ct_as_arrow_nav ">
<div class="ct_amy_arrows_next">
<i class="fa fa-angle-right next-arrow"></i>
</div>
<div class="ct_amy_arrows_prev">
<i class="fa fa-angle-left prev-arrow"></i>
</div>
</div>
<div id="arrownav2" class="ct_as_arrow_nav ">
<div class="ct_amy_arrows_next">
<i class="fa fa-angle-right next-arrow"></i>
</div>
<div class="ct_amy_arrows_prev">
<i class="fa fa-angle-left prev-arrow"></i>
</div>
</div>
You can do it like this:
$(this).closest(".ct_as_arrow_nav")
.find(".ct_amy_arrows_prev")
.removeClass("prev_show");;
Or like this:
$(this).parent()
.next(".ct_amy_arrows_prev")
.removeClass("prev_show");
Note: If the navs are dynamically created then consider binding the events like this!
Edit:
Change your initButtons to this:
function initButtons() {
jQuery('#arrownav' + sliderID + ' .next-arrow').click(gonext);
jQuery('#arrownav' + sliderID + ' .prev-arrow').click(goprev);
}
So that gonewt and goprev will have this bound to the arrow buttons.

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.

Categories

Resources