Dynamically add increment/decrement counter - javascript

I am trying to implement a dynamic increment/decrement counter. Here is how it should work:
I have an 'ADD' button. When i click on this, the same should disappear and a minus button, number input, plus button should appear. Clicking on "+" should increment the counter on the "cart" and clicking on "-" should decrement.
Below is html mycode
<body>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>
</body>
Jquery:
<script>
var addElement = 0;
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
}
addElement++;
});
var $input = $("#txtCounter");
// Initialise the value to 0
$input.val(0);
debugger;
// Increment/decrement count
$(".counter").click(function(){
console.log('here i am');
if ($(this).hasClass('increase'))
$input.val(parseInt($input.val())+1);
else if ($input.val()>=1)
$input.val(parseInt($input.val())-1);
});
});
</script>
Now the problem is after i add the dynamic +, text input counter, - controls, nothing happens when i click on + or minus. console.log inside $(".counter").click(function() is not giving anything.
Am i missing something??

You can do it like this: Adjust the $(".counter").click(function() {}); to $(document).on("click", ".counter", function(){}); as the element with the class counter isn't there when the page is initially loaded and therefore the click() event has to be delegated from a static parent element to the added counter element using on(). Move then the variable declaration var $input = $("#txtCounter"); inside this click function as the element with the id txtCounter isn't there when the page is initally loaded and move the initialization $("#txtCounter").val(0); after appending it.
var addElement = 0;
$(document).ready(function() {
$("#btnAddItem").on("click", function(event) {
if (addElement == 0) {
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
// Initialise the value to 0
$("#txtCounter").val(0);
}
addElement++;
});
// Increment/decrement count
$(document).on("click", ".counter", function() {
var $input = $("#txtCounter");
if ($(this).hasClass('increase')) {
$input.val(parseInt($input.val()) + 1);
} else if ($input.val() >= 1) {
$input.val(parseInt($input.val()) - 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>

You can change the script and try something like below:
var addElement = 0;
var myCounter= function(action){
var val = document.getElementById("txtCounter").value;
val = parseInt(val);
if(action == 2){ //Increase
document.getElementById("txtCounter").value=val+1;
}else if(val > 1){
document.getElementById("txtCounter").value=val-1;
}
};
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" onclick="myCounter(1);" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" value="0" /><button type="button" onclick="myCounter(2);" class="counter increase">+</button>'));
}
addElement++;
});
});

Related

Creating dynamic cards using jQuery

I'm doing an e-trade site with jQuery; however, when I increase then submit one of the products, they all get the properties of the first product. I defined the products as a json to a variable.
How can I create dynamic cards with jquery?
Here is how it looks:
İmage
Here is the source code:
$(document).on('click', '.number-spinner button', function() {
var btn = $(this),
oldValue = btn.closest('.number-spinner').find('input').val().trim(),
newVal = 0;
newVal = (btn.attr('data-dir') === 'up') ? parseInt(oldValue) + 1 : (oldValue > 1) ? parseInt(oldValue) - 1 : 0;
btn.closest('.number-spinner').find('input').val(newVal);
});
let html = data.reduce((acc, {name,value,image,counter,totalMoney}) =>
acc + `
<div class='card col-md-3'>
<img class='card-img-top' src="${image}" alt='Card image cap'>
<div class='card-body'>
<h5 class='card-title'>${name}</h5>
<p class="card-text">${value}</p>
<input class="money-input money" value="${value}"/>
<div class="number-spinner">
<div class="input-group number-spinner">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-minus" data-type="minus" data-dir="dwn"><span>-</span></button>
</span>
<input min="1" class="adet input-number" value="${counter}" type="number">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus" data-type="plus" data-dir="up"><span>+</span></button>
<div class="total-price"></div>
</span>
</div>
</div>
<button class="submit">Add To Card</button>
</div>
</div>`
, ``);
$('#list').append(html);
const adet = $(".adet").val()
const money = $(".money").val()
const totalMoney = adet * money;
var endText = 'Price'
var space = ' '
$( ".submit" ).click(function() {
$(".total-price").text($(".adet").val() * totalMoney);
$('.total-price').append( space + endText);
});
The "problem" is that you have (possibly) multiple elements with the class .adet and .money. However, the .val() method of a jQuery collection only extracts the value of the first element it contains. See the jQuery docs:
Get the current value of the first element in the set of matched elements...
jQuery docs

How to increment the counter value when the input field is filled?

This is my laravel view code. Here,I am trying to increment the counter value(ie.,value="0/5") . I have the input fields inside the modal and when clicking on the save button which is inside the model, the value should get incremented based on the filled input fields.ie(1/5..2/5..)
I have tried to increment those counter value.But it displays NaN
var val;
$("input").click(function() {
val = $('#counter').val();
val++;
$('#counter').prop('value', val)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>
<script type="text/javascript">
$("input").click(function() {
let val = parseInt($('#counter').val().split('/')[0]);
$('#counter').prop('value', `${++val}/5`);
});
</script>
Actually your code is working fine. Since you have the view inside a modal, which is only displayed or shown on a click event, you should use the jQuery "on" method to enhance your click handler function definition. In that case you should have your code working
var val;
$(document).on('click','#counter',function()
{
val = $('#counter').val();
val++;
$('#counter').prop('value',val )
});
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i>
Price,stock and Shipping Information<input type="submit" id="counter"
**value="0/5"** style="background-color: transparent; border:none">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
You can use regular expression to parse data before / character
var val;
$("input").click(function() {
val = $('#counter').val();
qty = val.match(/[^/]*/i)[0];
qty++;
$('#counter').prop('value', qty)
});
If you want to increase like this 1/5..2/5 .Use split and increase only upper value .
var val;
$("input").click(function() {
val = $('#counter').val().split("/");
//check eqal value with base
if(val[0] == val[1]) {
return false;
}
val[0]++;
$('#counter').prop('value', val[0]+"/"+val[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>
Here is your solution:
$("input").click(function() {
var val = $('#counter').val();
$('#counter').prop('value', `${++val % 6}/5`);
});
And a working fiddle:
https://jsfiddle.net/wv2x0mx5/4/
You can also try this.
$("#counter").on("click",function(){
var counterBtn = document.getElementById("counter");
var count = counterBtn.value;
//alert(count.split("/")[0]);
count = count.split("/");
counterBtn.value = ((parseInt(count[0])+1)%(parseInt(count[1])+1))+"/"+count[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>

append element to dynamically generated div using same classnames - Jquery

I have a toDo list for the very first list, I can add elements. I can also create multiple toDo lists dynamically, but while adding here it is been added to the very first list instead of the respective list where I click. Please someone help me, I am very new to JavaScript.
$toDoList = $('#toDoList');
$newTodoList = $('#newTodoList');
$parent = $('#parent');
$ul = $('ul');
$totalList = $('.totalList');
$(".remove").click(function() {
confirm('Are you sure? do you want to delete the item') ? $(this).parent().remove() : $(this);
});
$("li").click(function() {
$(this).hasClass("addBorder") ? $(this).removeClass("addBorder") : $(this).addClass("addBorder");
});
$('body').on('click', '.add', function() {
var itemName = $('#itemName').val();
var listItem = $('<li>' + itemName + '<button type="button" class="buttonStyle">-</button></li>');
listItem.on("click", function() {
confirm('Are you sure? do you want to delete the item') ? $(this).remove() : $(this);
});
$totalList.append(listItem);
$('#itemName').val('');
});
index = 1;
i = 1;
function addNewList() {
var newList = $('<div class="listParent" id="newList"><button type="button" class="addNewList" onClick="addNewList()">+</button><h2>My ToDO List!!</h2><ul id="toDoList" class="totalList"><li>Java script<button type="button" class="remove buttonStyle">-</button></li><li>Angular<button type="button" class="remove buttonStyle">-</button></li><li>Jasmine<button type="button" class="remove buttonStyle">-</button></li></ul><div class="inputText"><input type="text" id="itemName" class="leftmargin10" name="ListItem"><button type="button" id="addButton" class="buttonPlacement buttonStyle add">+</button></input></div></div>');
$('#newList').clone().attr('id', 'newList' + index++)
.insertAfter($('[id^=newList]:last'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" id="parent">
<div class="listParent" id="newList">
<button type="button" class="addNewList" onclick="addNewList()">+</button>
<h2>My ToDO List!!</h2>
<ul id="toDoList" class="totalList">
<li>Java script<button type="button" class="remove buttonStyle">-</button></li>
<li>Angular<button type="button" class="remove buttonStyle">-</button></li>
<li>Jasmine<button type="button" class="remove buttonStyle">-</button></li>
</ul>
<div class="inputText">
<input type="text" id="itemName" class="leftmargin10" name="ListItem"><button type="button" id="addButton" class="buttonPlacement buttonStyle add">+</button></input>
</div>
</div>
<!-- New list -->
The first thing I saw was that you are using multiple times the same id.
So I removed them all, since the "to do list" is to be cloned.
I simplified your code... I hope this will help.
// Remove (Delegate the clicks)
$(document).on("click",".remove",function(){
confirm('Are you sure? do you want to delete the item')? $(this).parent().remove():$(this);
});
// Li border (Delegate the clicks)
$(document).on("click","li",function(){
$(this).hasClass("addBorder")?$(this).removeClass("addBorder"):$(this).addClass("addBorder");
});
// Add a to do item to the list where the add button has been clicked.
$('body').on('click', '.add', function () {
// Find the relevant elements.
var thisParent = $(this).closest(".listParent");
var newTodoVal = thisParent.find(".newToDo");
var thisList = thisParent.find(".totalList");
// If there in a name inputed.
if(newTodoVal.val() !=""){
var listItem = "<li>"+newTodoVal.val()+"<button type='button' class='buttonStyle'>-</button>";
thisList.append(listItem);
newTodoVal.val('');
}
});
// Clone the last list to create a new one.
$(".addNewList").on("click",function(){
var lastList = $(".listParent").last();
lastList.clone().insertAfter(lastList);
});
.addBorder{
border:1px solid black;
max-width:10em;
}
.leftmargin10{
margin-left:10px;
}
.buttonStyle{
margin-left:0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<button type="button" class="addNewList">+</button>
<div class="listParent">
<h2>My ToDO List!!</h2>
<ul class="totalList">
<li>Java script<button type="button" class="remove buttonStyle">-</button></li>
<li>Angular<button type="button" class="remove buttonStyle">-</button></li>
<li>Jasmine<button type="button" class="remove buttonStyle">-</button></li>
</ul>
<div class="inputText">
<input type="text" class="leftmargin10 newToDo" name="ListItem">
<button type="button" class="buttonPlacement buttonStyle add">+</button>
</div>
</div>
<!-- New list -->
</div>
I assume that you click the + to add an item to a list.
You have this line of code:
$totalList.append(listItem);
In theory that should append listItem to every list which has class='totalList', I think you want it added only to the list where the + button was clicked, so I would change that line to
$(this).closest('.totalList').append(listItem);

Dynamically generated button remove by onClick in jQuery

I have inserted button by onclick in a way that if you click on the button then it will append within <div id="article-tags"></div> just like the below image,
To create that, I have arranged the HTML code segment below:
<div id="article-tags">
</div>
<div>
<button type="button" data-id="1" data-name="tag" class="tag-item">tag</button>
<button type="button" data-id="2" data-name="tag2" class="tag-item"> tag2</button>
<button type="button" data-id="3" data-name="tag3" class="tag-item">tag3</button>
<button type="button" data-id="4" data-name="tag4" class="tag-item">tag4</button>
</div>
And the jQuery code segment is below,
$(".tag-item").click(function(){
var btnid = $(this).data("id");
var btnname = $(this).data("name");
$("#article-tags").append("<button type='button' class='tag-selected ntdelbutton'>"+ btnname +" <i class='fa fa-times-circle' aria-hidden='true'></i></button>");
$(this).css({"background-color": "#DFE2E5", "color": "#ababab"});
$(this).attr("disabled", true);
return false;
});
But right now, I would like to remove the button by onClick that is populated within
<div id="article-tags"></div>
I have tried to by using the following jQuery code segment below:
$(".tag-selected").click(function(){
$(this).remove();
});
or
$(".tag-selected").live("click", function() {
$(this).remove();
});
But neither is working. Please help me to solve this problem.
Try following code. Do you want to restore 'disabled': false attribute after removing specified element?
$(".tag-item").click(function() {
var btnid = $(this).data("id");
var btnname = $(this).data("name");
$("#article-tags").append("<button type='button' class='tag-selected ntdelbutton'>" + btnname + " <i class='fa fa-times-circle' aria-hidden='true'></i></button>");
$(this).css({
"background-color": "#DFE2E5",
"color": "#ababab"
});
$(this).attr("disabled", true);
$(".ntdelbutton").click(function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article-tags">
</div>
<div>
<button type="button" data-id="1" data-name="tag" class="tag-item">tag</button>
<button type="button" data-id="2" data-name="tag2" class="tag-item"> tag2</button>
<button type="button" data-id="3" data-name="tag3" class="tag-item">tag3</button>
<button type="button" data-id="4" data-name="tag4" class="tag-item">tag4</button>
</div>
Here is an approach using plain javascript (rather than the jQuery library) and a dash of CSS:
var upperButtons = document.querySelectorAll('.upper button');
var lowerButtons = document.querySelectorAll('.lower button');
for (let i = 0; i < lowerButtons.length; i++) {
lowerButtons[i].addEventListener('click', function(){upperButtons[i].style.visibility = 'visible'; lowerButtons[i].setAttribute('disabled','disabled');}, false);
}
for (let i = 0; i < upperButtons.length; i++) {
upperButtons[i].addEventListener('click', function(){upperButtons[i].removeAttribute('style'); lowerButtons[i].removeAttribute('disabled');}, false);
}
.upper button {
visibility: hidden;
}
<div class="upper">
<button type="button">tag</button>
<button type="button">tag2</button>
<button type="button">tag3</button>
<button type="button">tag4</button>
</div>
<div class="lower">
<button type="button">tag</button>
<button type="button">tag2</button>
<button type="button">tag3</button>
<button type="button">tag4</button>
</div>

How to get the value of a particular input field using id in the html templates

I have two div html elements with different id and here I am using spinner. Whenever values in the spinner input changes alert box will be displayed.
HTML code
<div id="accordion2" class="panel-group" style="display: block;">
<div id="accordion2" class="panel-group">
<div id="Tea">
<div class="spinner Tea input-group ">
<input type="text" id = "servings" class="form-control input- sm" value="Tea"/>
<div class="input-group-btn-vertical">
<button class="btn Tea btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Tea btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Tea"> Tea </h4>
</div>
<div id="Coffee">
<div class="spinner Coffee input-group ">
<input type="text" id = "servings" class="form-control input-sm" value="Coffee"/>
<div class="input-group-btn-vertical">
<button class="btn Coffee btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Coffee btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Coffee">Coffee</h4>
</div>
</div>
</div>
JQuery code
$(function(){
$('.spinner:first-of-type input').on('click', function() {
$('.spinner:first-of-type input').val(parseInt($('.spinner:first-of-type input').val(), 10) + 1);
var val = $('.spinner:first-of-type input').val();
changeValues(val);
});
$('.spinner:last-of-type input').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
function changeValues(value){
alert($('#energy').attr('class').split(' '));
};
});
But in the alert box whenever I click the spinner up arrow only Tea is displayed.
what I expect is when the spinner is clicked from Tea div tea should be displayed and when from coffee , coffee should be displayed.Please help me out
I'm not sure I totally got what you are trying to do, but it seems to me that you want to increment and decrement number of beverage cups on up/down buttons click. For this you would better modify mark up a little (remove duplicated ids, add classes for convenience). And I may look like this then:
$(function() {
$('.spinner').on('click', '.servings', function(e) {
$(this).val(parseInt($(this).val() || 0, 10) + 1);
var val = $(this).val();
changeValues.call(e.delegateTarget, val);
})
.on('click', '.up', function(e) {
$(e.delegateTarget).find('.servings').val(function() {
return ++this.value;
});
})
.on('click', '.down', function(e) {
var $input = $(e.delegateTarget).find('.servings');
if (+$input.val() > 1) {
$input.val(function() {
return --this.value;
});
}
});
function changeValues(value) {
var type = $(this).find('.energy').data('type');
alert(type);
};
});
Demo: http://plnkr.co/edit/9vXC0RipxkzqhXrHJAKD?p=preview
try this:
$(function () {
$('.spinner').each(function () {
var $el = $(this),
$buttons = $el.find('button'),
$h4 = $el.find('h4'),
input = $el.find('input').get(0);
function showAlert() {
alert($h4.get(0).className);
}
$buttons.eq(0).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) + 1;
showAlert();
});
$buttons.eq(1).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) - 1;
});
});
});
JSFiddle http://jsfiddle.net/yLtn57aw/2/
Hope this helps

Categories

Resources