I'm trying to make a toggle switch work, which will show/hide classes based on if it is checked or unchecked. By default i want to show "pay annually" so it will display the annual price, also a text blub further down the page. If i click "pay monthly" it will display the monthly price, and a monthly text blurb further down the page.
I tried to follow some solution, but at the moment all are showing, and nothing toggles. How can i fix this?
link to codepen
function showHide(e) {
const el = e.target;
if (el.checked) {
el.dataset.checked.split(',').forEach(fld => document.getElementById(fld).parentNode.style.display = 'block');
el.dataset.notChecked.split(',').forEach(fld => document.getElementById(fld).parentNode.style.display = 'none' );
} else {
el.dataset.checked.split(',').forEach(fld => document.getElementById(fld).parentNode.style.display = 'none' );
el.dataset.notChecked.split(',').forEach(fld => document.getElementById(fld).parentNode.style.display = 'block');
}
}
Using jQuery :
$(document).ready(function() {
var checkBoxes = $("input[name='toggle']");
toggle();
$("#toggle").click(function() {
toggle();
});
function toggle() {
if (checkBoxes.prop("checked")) {
$('#coreMonthlyText,#coreMonthlyPrice').show('slow');
$('#coreAnnuallyText,#coreAnnuallyPrice').hide('slow');
} else {
$('#coreMonthlyText,#coreMonthlyPrice').hide('slow');
$('#coreAnnuallyText,#coreAnnuallyPrice').show('slow');
}
}
});
.pricing-box {
background: red;
padding: 25px
}
.row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
}
.column {
display: flex;
flex-direction: column;
flex-basis: 100%;
flex: 1;
}
.toggle-switch {
cursor: pointer;
background-color: gray;
display: inline-block;
border: 0;
padding-left: 0;
padding-right: 0;
}
.toggle-switch input {
display: none;
}
.toggle-switch,
.toggle-switch span {
border-radius: 35px;
border-style: solid;
border-color: transparent;
padding-top: .75rem;
padding-bottom: .75rem;
}
.toggle-switch span {
border-width: 2px;
padding-left: .75rem;
padding-right: .75rem;
}
.toggle-switch input:checked+span+span,
.toggle-switch input+span {
border-color: #444;
background-color: white;
}
.toggle-switch input+span+span,
.toggle-switch input:checked+span {
background-color: transparent;
border-color: transparent;
}
#coreMonthlyText,
#coreMonthlyPrice,
#coreAnnuallyText,
#coreAnnuallyPrice {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricing-box">
<div class="row">
<div class="column">
<div class="core">
<h2>Core</h2>
</div>
</div>
<div class="column">
<div id="coreAnnuallyPrice" class="coreAnnuallyPrice">
$2,399/yr<br /> Normally $3,588/yr
</div>
<div id="coreMonthlyPrice" class="coreMonthlyPrice">
$299/pm<br /> first 2 months free
</div>
</div>
</div>
<label for="toggle" class="toggle-switch">
<input class="toggle-button" id="toggle" type="checkbox" name="toggle" data-checked="coreAnnuallyPrice,coreAnnuallyText" data-not-checked="coreMonthlyPrice,coreMonthlyText">
<span>pay annually</span>
<span>pay monthly</span>
</label>
</div>
<p id="coreAnnuallyText" class="center_text big-text coreAnnuallyText">this is a annual text blurb</p>
<p id="coreMonthlyText" class="center_text big-text coreMonthlyText">this is a monthly text blurb.</p>
Related
there is a filter on the js, which consists of three identical buttons (named "green", "yellow", "red"), which are responsible for setting/removing the blur effect for the set of pictures located below.
When pressing the "green" button, a blur effect should be set for all pictures that have a value "green" of data-card property.
At the second click on the same button, the blur effect should be canceled for this category of pictures.
I solved this problem with a reception with a boolean flag:
let firstClick = true;
if (firstClick){
//..do at first click
firstClick = !firstClick;
}
else{
//..do at second click
firstClick = !firstClick;
}
However, the problem occurs when I click on the "green" button (this is the first click on the "green" button), and after that on another button, for example "red" (this is the first click on the "red" button). But the compiler perceives a click on the "red" button as a second click, although it is a different button.
The question is how to distinguish the behavior in different buttons?
In general, I solved the problem through a complete search and many if statements. Maybe there is an alternative way?
Project demo in codepen
//main.js
function app() {
const buttons = document.querySelectorAll('.service__btn');
const cards = document.querySelectorAll('.service__item');
let firstClick = true;
function setBlour(listOfCards) {
listOfCards.forEach(item => {
if (item.classList.contains(currentCategory)) {
item.classList.add('blur');
}
});
}
function resetBlour(listOfCards) {
listOfCards.forEach(item => {
if (item.classList.contains(currentCategory)) {
item.classList.remove('blur');
}
});
}
function highlightButton(butt) {
if (!butt.classList.contains('service__btn__clicked')) {
butt.classList.add('service__btn__clicked');
}
firstClick = !firstClick;
}
function unhighlight(butt) {
if (butt.classList.contains('service__btn__clicked')) {
butt.classList.remove('service__btn__clicked');
}
firstClick = !firstClick;
}
buttons.forEach(button => {
button.addEventListener('click', (event) => {
currentCategory = event.target.dataset.filter; //current category we get from clicked button
let matchedCards = document.querySelectorAll(`[data-card="${button.dataset.filter}"]`);
//is it first click?
if (firstClick) {
if (!matchedCards[0].classList.contains('blur')) { // each click we have set of matchedCards, it's easy to check one of them (the first for example) if it have blur
setBlour(matchedCards);
highlightButton(button);
} else { //it is a first clcik, but card have blur - so remove blur
resetBlour(matchedCards);
unhighlight(button);
}
}
//second click
else {
if (!matchedCards[0].classList.contains('blur')) { //if there is no blur - add blur
setBlour(matchedCards);
highlightButton(button);
} else { //second click and blur is present - so we need to remove it
resetBlour(matchedCards);
unhighlight(button);
}
}
});
});
}
app()
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
li {
list-style-type: none;
}
.container {
width: 1220px;
margin: 0 auto;
}
.service {
background: #EDF2EC;
padding-top: 40px;
padding-bottom: 70px;
}
.service__top {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.service__top-title {
font-family: 'Inika', serif;
font-weight: 400;
font-size: 40px;
line-height: 52px;
color: #499A18;
max-width: 306px;
}
.service__filter-btn {
margin-left: 142px;
}
.service__btn {
border: 1px solid #E06733;
border-radius: 5px;
padding: 12px 40px;
font-family: 'Inika', serif;
font-weight: 400;
font-size: 20px;
line-height: 26px;
color: #E06733;
}
.service__btn__clicked {
background: #E06733;
border: 1px solid #E06733;
border-radius: 5px;
color: #FFFFFF;
}
.service__btn+.service__btn {
margin-left: 32px;
}
.service__content {
column-count: 3;
gap: 0 116px;
}
.service__item {
margin-bottom: 55px;
text-align: center;
width: 330px;
height: 350px;
border-radius: 20px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.service__item-title {
font-family: 'Inter', sans-serif;
font-weight: 700;
font-size: 20px;
line-height: 20px;
color: #E06733;
margin-top: 10px;
margin-bottom: 10px;
}
.service__item-text {
font-family: 'Inter', sans-serif;
font-weight: 400;
font-size: 16px;
line-height: 20px;
color: #717171;
margin-bottom: 36px;
}
.service__item-description {
border-radius: 0px 0px 20px 20px;
border: 1px solid #e3e1d5;
display: none;
}
.blur {
filter: blur(5px);
}
.animation {
transform: scale(0);
opacity: 0;
}
<body>
<section class="service">
<div class="container">
<div class="service__top">
<h3 class="service__top-title">
Caption and Description
</h3>
<div class="service__filter-btn">
<button class="service__btn service__btn-type_green" data-filter="green"> Green</button>
<button class="service__btn service__btn-type_yellow" data-filter="yellow">Yellow</button>
<button class="service__btn service__btn-type_red" data-filter="red">Red</button>
</div>
</div>
<div class="service__content">
<div class="service__item green" data-card="green">
<div class="service__item-description">
<h4 class="service__item-title">Green color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item yellow" data-card="yellow">
<div class="service__item-description">
<h4 class="service__item-title">Yellow color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item green" data-card="green">
<div class="service__item-description">
<h4 class="service__item-title">Green color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
</div>
</div>
</section>
</body>
I am trying to solve this problem with my mini game using javascript. The Game is suppose to randomly show divs using the randomFadeIn with jquery.random-fade-in.min.js. It works but the problem is that I could not stop it from running. This is just a basic javascript game but it is hard to implement using jquery
Here is my full code
const result = document.getElementById(".box-container>div");
console.log(result);
const button = document.getElementsByTagName("div");
let sec = 0;
function gameStart(num) {
let num1 = 800;
if ($(".box-container>div>p").css('opacity') != 0) {
console.log("not yet done");
$(function() {
$('.box-container').randomFadeIn(800);
});
} else {
console.log("win");
};
}
function clickBox() {
$(".box-container>div>p").click(function() {
$(this).animate({
opacity: 0
}, 800);
})
}
function gameWins() {}
function gameStops() {
setTimeout(function() {
alert("Game Ends");
}, 60000);
}
clickBox();
//gameStops();
gameWins();
.box-container {
width: 232px;
float: left;
width: 45%;
}
.box-container div {
float: left;
height: 100px;
margin-bottom: 8px;
margin-right: 8px;
overflow: hidden;
width: 100px;
}
.box-container div p {
background: #097;
box-sizing: border-box;
color: #fff;
display: none;
font-size: 20px;
height: 100%;
margin: 0;
padding-top: 14px;
text-align: center;
width: 100%;
}
.clearfix:after {
clear: both;
content: '';
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://sutara79.github.io/jquery.random-fade-in/dist/jquery.random-fade-in.js"></script>
<h1> Click Dem Boxes</h1>
<button onclick="gameStart()"> Start game </button>
<p>Mechanics: You need to click all the boxes before the time ends</p>
> just a bunch of divs that fades in and does not stop
<div class="box-container clearfix">
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
By using the .stop() function, you could stop the animation. See snippet below.
let maxSeconds = 30000;
let numOfCards = $('.box').length;
function gameStart() {
console.log("Game started");
let numOfClicked = 0;
$(".box-container>div>p").click(function() {
// Increase the counter
numOfClicked++;
// Fade out
$(this).fadeOut(800);
if(numOfClicked == numOfCards){
gameWon();
}
})
$('.box-container').randomFadeIn(800);
setTimeout(
function() {
if(numOfClicked != numOfCards){
gameLost();
}
}, maxSeconds);
}
function gameWon(){
gameStop();
console.log("You won the game!");
}
function gameLost(){
gameStop();
console.log("You lost the game!");
}
function gameStop(){
$(".box-container>div>p").stop(false, false);
}
.box-container {
width: 232px;
float: left;
width: 45%;
}
.box-container div {
float: left;
height: 100px;
margin-bottom: 8px;
margin-right: 8px;
overflow: hidden;
width: 100px;
}
.box-container div p {
background: #097;
box-sizing: border-box;
color: #fff;
display: none;
font-size: 20px;
height: 100%;
margin: 0;
padding-top: 14px;
text-align: center;
width: 100%;
}
.clearfix:after {
clear: both;
content: '';
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://sutara79.github.io/jquery.random-fade-in/dist/jquery.random-fade-in.js"></script>
<h1> Click Dem Boxes</h1>
<button onclick="gameStart()"> Start game </button>
<p>Mechanics: You need to click all the boxes before the time ends</p>
> just a bunch of divs that fades in and does not stop
<div class="box-container clearfix">
<div class="box">
<p></p>
</div>
<div class="box">
<p></p>
</div>
<div class="box">
<p></p>
</div>
<div class="box">
<p></p>
</div>
<div class="box">
<p></p>
</div>
</div>
I'm trying to create a custom drop down menu, using HTML, CSS and Vanilla Javascript.
I've managed to get the menu to appear when the user clicks on the the "from" input field, however when I try and click on an option, it wont let you add the value stored in the "code" dataset.
I did get it to work by using setTimeout method, however it is a bit hit and miss sometimes and doesn't seem like a good solution.
Is there an alternative way to get it to work?
function app() {
var messages = document.querySelector(".messages");
var inputFrom = document.querySelector(".input-from");
var inputTo = document.querySelector(".input-to");
var nearestContainer = document.querySelector(".nearest-container");
inputFrom.addEventListener("focus", inputToFocusIn, false);
function inputToFocusIn(e) {
messages.innerHTML = "focusin event triggered on input-from";
// add class
inputFrom.classList.add("input-from--focusin");
nearestContainer.classList.add("nearest-container--active");
// remove class
inputFrom.classList.remove("input-from--focusout");
nearestContainer.classList.remove("nearest-container--hidden");
}
inputFrom.addEventListener("focusout", inputToFocusOut, false);
function inputToFocusOut(e) {
messages.innerHTML = "focusout event triggered on input-from";
// add class
inputFrom.classList.remove("input-from--focusin");
nearestContainer.classList.remove("nearest-container--active");
// remove class
inputFrom.classList.add("input-from--focusout");
nearestContainer.classList.add("nearest-container--hidden");
}
var nearestStations = document.querySelectorAll(".nearest-station");
// add event listener to buttons
for(var nearestStation of nearestStations) {
nearestStation.addEventListener("click", addToInputFrom, false);
}
function addToInputFrom(e) {
inputFrom.classList.add("input-from--focusout");
nearestContainer.classList.add("nearest-container--hidden");
inputFrom.classList.remove("input-from--focusin")
nearestContainer.classList.remove("nearest-container--active")
var targetDataset = e.currentTarget.dataset.code;
messages.innerHTML = "station added to input from field"
inputFrom.value = "";
inputFrom.value = targetDataset;
}
var switchButton = document.querySelector(".button-switch");
switchButton.addEventListener("click", clickSwitch, false);
function clickSwitch(e) {
var inputFromValue = inputFrom.value;
var inputToValue = inputTo.value;
inputFrom.value = inputToValue;
inputTo.value = inputFromValue;
}
}
window.onload = app();
/* stylesheet */
body {
font-family: "GRAPHIK";
font-style: normal;
font-weight: 400;
font-size: 16px;
color: #242424;
}
* {
box-sizing: border-box;
outline: none;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
background-color: #FF4136;
}
.search-container {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 300px;
padding: 10px;
background-color: #FFF;
border-radius: 10px;
}
.form-container {
display: flex;
flex-direction: row;
width: 100%;
}
.input-container {
width: 100%;
}
.input {
width: 100%;
border: none;
border-radius: 10px;
background-color: #f1f1f1;
padding: 10px;
}
.input-from {
margin-bottom: 5px;
}
.input-from--focusout {
border-radius: 10px;
}
.input-from--focusin {
border-radius: 10px 10px 0 0;
}
.input-to {
margin-bottom: 5px;
}
.switch-container {
margin-bottom: 5px;
}
.button {
border: none;
background-color: transparent;
}
.button-switch {
height: 100%;
width: 38px;
margin-left: 5px;
background-color: #f1f1f1;
border-radius: 10px;
background-image: url(../assets/images/switch.svg);
background-position: center;
background-size: 20px;
background-repeat: no-repeat;
}
.button-switch:hover {
background-image: url(../assets/images/switch-hover.svg);
}
.button-search {
padding: 10px;
background-color: #2ECC40;
color: #FFF;
border-radius: 10px;
width: 100%;
transition: background-color 0.5s ease;
}
.button-search:hover {
background-color: #33e147;
}
.input-container-to {
position: relative;
}
.nearest-container {
position: absolute;
top: 38px;
background-color: #f1f1f1;
padding: 5px;
border-radius: 0 0 10px 10px;
width: 100%;
z-index: 100;
}
.messages {
width: 300px;
background-color: #FFF;
padding: 5px;
border-radius: 10px;
text-align: center;
margin-bottom: 5px;
font-size: 10px;
}
.finding, .show-more {
width: 100%;
font-size: 10px;
font-style: italic;
margin: 0;
padding: 5px;
}
.show-more {
text-align: center;
}
.nearest-station {
font-size: 10px;
padding: 5px;
border-radius: 10px;
}
.nearest-container--hidden {
display: none;
}
.nearest-station--active {
display: flex;
}
.nearest-station:hover {
background-color: #FFF;
cursor: pointer;
}
.logo {
margin-right: 5px;
}
.nr-logo {
width: 15px;
}
.station-distance {
font-style: italic;
float: right;
}
<div class="container">
<div class="messages">messages here</div>
<div class="search-container">
<div class="form-container">
<div class="input-container">
<div class="input-container-to">
<input type="text" class="input input-from" placeholder="From">
<div class="nearest-container nearest-container--hidden">
<div class="stations-container">
<p class="finding">Finding stations closest to you...</p>
<!-- stations here-->
<div class="nearest-station" data-code="Leigh-on-Sea">
<span class="logo"><img class="nr-logo" src="assets/images/nr-logo.svg"></span>
<span class="station-name">Leigh-on-Sea</span>
<span class="station-distance">0.6km</span>
</div>
<div class="nearest-station" data-code="Chalkwell">
<span class="logo"><img class="nr-logo" src="assets/images/nr-logo.svg"></span>
<span class="station-name">Chalkwell</span>
<span class="station-distance">1.5km</span>
</div>
<div class="nearest-station" data-code="Westcliff">
<span class="logo"><img class="nr-logo" src="assets/images/nr-logo.svg"></span>
<span class="station-name">Westcliff</span>
<span class="station-distance">2.7km</span>
</div>
<div class="nearest-station" data-code="Southend Central">
<span class="logo"><img class="nr-logo" src="assets/images/nr-logo.svg"></span>
<span class="station-name">Southend Central</span>
<span class="station-distance">3.6km</span>
</div>
<div class="nearest-station" data-code="Southend Victoria">
<span class="logo"><img class="nr-logo" src="assets/images/nr-logo.svg"></span>
<span class="station-name">Southend Victoria</span>
<span class="station-distance">3.8km</span>
</div>
</div>
<div class="stations-show-more">
<!--
<p class="show-more">Show more stations</p> -->
</div>
</div>
</div>
<div class="input-container-to">
<input type="text" class="input input-to" placeholder="To">
</div>
</div>
<div class="switch-container">
<input type="button" class="button button-switch">
</div>
</div>
<div class="button-search-container">
<input type="button" class="button button-search" value="Search">
</div>
</div>
</div>
Using setTimeout in the inputToFocusOut() function is indeed the correct way to obtain the desired effect: hiding of the menu must be delayed so that a click on a menu item will register and its callback will fire. There should be nothing hit and miss about it, just set the delay at a reasonable value, say 300ms, and remove the hiding of the menu from the addToInputFrom() callback. Actually, you can remove all of the latter function's class-toggling calls, as they are redundant there and may interfere. The menu will be shown/hidden by virtue of inputFrom gaining/losing focus.
BTW, why are you using focusout and not blur?
Using focusout event here
inputFrom.addEventListener("focusout", inputToFocusOut, false);
is not right. Because it will be triggered before click event.
When the function inputToFocusOut is executed the .nearest-container becomes hidden:
nearestContainer.classList.add("nearest-container--hidden");
and that's why click event for it and all of its child nodes (we are interested in .nearest-station elements) won't be triggered. Instead of focusout, use mousedown event. With blur event it won't work.
I wrote some code with three things in mind:
Highlighting a selection's border using 'on click'.
Selecting one item will remove the highlight from the other item.
The ability to deselect each item on click.
I've managed to get everything working for the most part, but I don't particularly like how complex the code is for the radial dot that appears when one item is selected.
Below is an example of what I'm talking about, particularly I'm looking for ways to refactor the code below into something a little more legible (shorter).
$(this).children('.radial').children().toggleClass('checked').parents('.itembox')
.siblings().children('.radial').children().removeClass('checked');
Here's a working example for more context (line 10):
var raceInternet = false;
var racePhone = false;
var raceTv = false;
$(function() {
var $targetDiv = $('#race-internet > .itembox');
var $radialDot = $('.radial > .center-dot');
$targetDiv.on('click', function() {
$(this).toggleClass('user-selected').siblings().removeClass('user-selected');
//Is it possible to refactor Line 10?
$(this).children('.radial').children().toggleClass('checked').parents('.itembox').siblings().children('.radial').children().removeClass('checked');
if ($targetDiv.is('.user-selected')) {
raceInternet = true;
} else {
raceInternet = false;
}
})
})
.itembox-container {
display: flex;
}
.boxes-2 {
width: calc((100% - 25px)/2);
margin: 10px;
padding: 10px;
}
.itembox {
position: relative;
display: inline-block;
border: 5px solid #e8e8e8;
border-radius: 10px;
cursor: pointer;
}
.user-selected {
border: 5px solid #E16E5B;
}
.itembox h4 {
color: #22ddc0;
font-weight: 700;
}
span.price {
display: inline-block;
font-weight: 400;
float: right;
color: #22ddc0;
}
.itembox > ul {
list-style: none;
}
.itembox > ul > li {
line-height: 3;
}
.radial {
position: absolute;
float: right;
height: 35px;
width: 35px;
padding: 2px;
border: 5px solid #e8e8e8;
border-radius: 50%;
top: 43%;
right: 10px;
}
.center-dot {
display: none;
position: relative;
height: 21px;
width: 21px;
background-color: #E16E5B;
border-radius: 50%;
}
.checked {
display: block;
}
.prime-aux:first-of-type {
top: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
<!-- Primary Content Container -->
<div class="prime-aux">
<div id="race-internet" class="itembox-container">
<div class="itembox boxes-2">
<h4>Gigabit Internet <span class="price">$60/mo</span></h4>
<ul>
<li>1,000 Mbps</li>
<li>No data caps</li>
</ul>
<div class="radial">
<div class="center-dot"></div>
</div>
</div>
<div class="itembox boxes-2">
<h4>Basic Internet <span class="price">$25/mo</span></h4>
<ul>
<li>25 Mbps</li>
<li>No data caps</li>
</ul>
<div class="radial">
<div class="center-dot"></div>
</div>
</div>
</div>
</div>
</section>
<!-- Primary Content Container End -->
View on JS Fiddle
You can eliminate a lot of your jQuery by just leveraging CSS. Typically, if I want to toggle a feature, I have it either display: block; or display: none; based upon a CSS selector. Then, I just use jQuery to toggle the parent element's class name. So for example:
.item.selected .checkmark {
display: block;
}
.item .checkmark {
display: none;
}
$('.item').click(function(){ $(this).toggleClass('selected') });
JSFiddle
DEMO
I'am trying to select only 3 Items at a time, As of now all the elements are being selected. please guide
"If user want to select other element first user want to unselect the
selected Images.. "
JS :
var getTagsNameArray = [];
$('.q2 .product-multiple').on('click', function(e) {
var item = $(this).find('img').attr('name');
if ($(this).hasClass('selectTag')) {
$(this).removeClass('selectTag');
getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
} else {
$(this).addClass('selectTag');
getTagsNameArray.push(item);
}
console.log(getTagsNameArray.join(', '));
});
$('.q2-get-answer').on('click', function() {
console.log(getTagsNameArray.join(', '));
})
As you are adding .selectTag to the selected element. Simply compare length of the elements having class as selectTag.
Edit: As suggested by Shady Alset, If count of selected elements is 3 user clicks on selected item,unselect is implemented.
var getTagsNameArray = [];
$('.q2 .product-multiple').on('click', function(e) {
if ($('.selectTag').length < 3) {
var item = $(this).find('img').attr('name');
if ($(this).hasClass('selectTag')) {
$(this).removeClass('selectTag');
getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
} else {
$(this).addClass('selectTag');
getTagsNameArray.push(item);
}
console.log(getTagsNameArray.join(', '));
} else {
if ($(this).hasClass('selectTag')) {
$(this).removeClass('selectTag');
getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
} else {
alert('3 items are already selected!')
}
}
});
$('.q2-get-answer').on('click', function() {
console.log(getTagsNameArray.join(', '));
})
.product-multiple {
float: left;
margin: 10px;
}
.product-multiple img {
width: 200px;
height: 150px;
}
.product-multiple img:hover {
cursor: pointer;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
cursor: pointer;
}
.digestive-tool {
padding: 10px;
margin: 10px;
border: 1px solid #ccc;
}
.digestive-tool .q1-answer li,
.digestive-tool .q2-answer li,
.digestive-tool .q3-answer li,
.digestive-tool .q4-answer li,
.digestive-tool .q5-answer li,
.digestive-tool .q6-answer li {
list-style-type: none;
display: inline-block;
}
.digestive-tool .q1-get-answer,
.digestive-tool .q2-get-answer,
.digestive-tool .q3-get-answer,
.digestive-tool .q4-get-answer,
.digestive-tool .q5-get-answer,
.digestive-tool .q6-get-answer {
border: 1px solid #f00;
padding: 10px;
display: inline-block;
cursor: pointer;
}
.digestive-tool .product,
.digestive-tool .product-multiple {
display: inline-block;
}
.digestive-tool .product img,
.digestive-tool .product-multiple img {
width: 150px;
height: 180px;
cursor: pointer;
}
.selectTag {
border: 2px solid #00257a;
}
.q2-get-answer {
margin-top: 20px;
clear: left;
border: 1px solid #900;
background: #f00;
cursor: pointer;
width: 200px;
padding: 20px;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="q2">
<label for="q2">how to keep a limit of only 3 selection values</label>
<div class="q2-answer" id="q2">
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="gassy">
<div>Gassy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="fussy">
<div>Fussy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="diahrea">
<div>Diahrea</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="spitup">
<div>Spit Up</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="constipation">
<div>Constipation</div>
</div>
</div>
<div class="q2-get-answer">
Q3 click me
</div>
</div>
Fiddle here
You probably need to add below check before addClass.
else if ($('.selectTag').length < 3)
Complete code block.
if ($(this).hasClass('selectTag')) {
$(this).removeClass('selectTag');
getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
} else if ($('.selectTag').length < 3) {
$(this).addClass('selectTag');
getTagsNameArray.push(item);
}