Update atrribute value on click in dynamic table cell span - javascript

How do I make the Up buttons to update the attribute value? When I increase the count fx to 5 and then decrease it with Down buttons to 2, and then increase it again, it does not increase from the current value of attr value wich is 2 but continues from 5. I just don't know how to update it after Down button has been clicked. DEMO
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).each(function(index, element) {
var count= $(element).closest('tr').find('.times').attr('data-myval');
$(element).click(function() {
count++;
$(element).closest('tr').find('.times').attr('data-myval', count);
$(element).closest('tr').find('.times').text(count +' x');
});
});
$(minus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr')
.find('.times').attr('data- myval');
count--;
parseInt($(element).closest('tr')
.find('.times').attr('data-myval',count))
$(element).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(element).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
});

Please set the countinside the click event for the up button:
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr').find('.times').attr('data-myval');
count++;
$(element).closest('tr').find('.times').attr('data-myval', count);
$(element).closest('tr').find('.times').text(count +' x');
});
});
$(minus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr')
.find('.times').attr('data- myval');
count--;
parseInt($(element).closest('tr')
.find('.times').attr('data-myval',count))
$(element).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(element).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
});
I hope that helps :D

I refactored your code to avoid putting click handlers inside of a loop. jQuery lets you listen to click events on a per class basis without expressly defining each one.
The contents of each function is largely unchanged, I just saved the elements we need to look up in variables to avoid looking them up repeatedly.
Your problem in the code posted was count being set outside of the click handler. That logic has been moved inside of the .up click handler.
Fiddle
Javascript
$(function() {
$('.up').on('click', function(){
var count = $(this).closest('tr').find('.times');
var curVal = Number(count.attr('data-myval'));
count.attr('data-myval', curVal + 1);
count.text(curVal + 1 + ' x');
})
$('.down').on('click', function(){
var count = $(this).closest('tr').find('.times');
var curVal = Number(count.attr('data-myval'));
curVal--;
count.attr('data-myval', curVal);
count.text(curVal + ' x');
if (curVal < 2) {
count.text('');
}
if (curVal < 1) {
$(this).parents('tr').remove();
}
})
});

I'm guessing you are setting the count outside of the onclick function
var count= $(element).closest('tr').find('.times').attr('data-myval');
So the count may hold the previous value that was set when the last up was pressed.

grab the value first in count variable then increment i update your jsfiddle, i hope its helpful for you
var count = $(element).closest('tr').find('.times').attr('data-myval');
count++;
https://jsfiddle.net/j9vnbcf0/13/

You just don't need to go through for .each function for each plus/minus btns, simply call .click function on them directly, it works that way-
JS-
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).click(function() {
var count= $(this).closest('tr').find('.times').attr('data-myval');
count++;
// console.log(count);
$(this).closest('tr').find('.times').attr('data-myval', count);
$(this).closest('tr').find('.times').text(count +' x');
});
$(minus).click(function() {
var count= $(this).closest('tr').find('.times').attr('data-myval');
count--;
parseInt($(this).closest('tr').find('.times').attr('data-myval',count))
$(this).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(this).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
Here goes the updated link-
https://jsfiddle.net/j9vnbcf0/14/

Related

Javascript counter++ skips counting

I am building a simple JS game but ++ keeps on adding up for no reason.
Here is the code:
var cities = ["Atlanta","Chicago","Honolulu","Houston","Nashville","Orlando","Philadelphia","Phoenix","Portland","Seattle"],
c = Math.floor((Math.random() * 10)),
city = cities[c].toUpperCase(),
cityArr = city.split(""),
length = city.length,
guess = 0,
$prompt = $('#prompt'),
x, //letter guess
i;
function randomCity() {
var $showCity = document.getElementById("showCity"), //ul
newLi,
letter;//each letter of city
for(i=0; i<cityArr.length; i++){
newLi = document.createElement("li");
$showCity.appendChild(newLi);
letter = document.createTextNode(cityArr[i]);
newLi.appendChild(letter);
}
$("#showCity li").css("color", "#fff");
}//end randomCity()
function play() {
if(guess == 6){
$("#alphabet").css("visibility", "hidden");
ending();
} else {
$prompt.fadeIn("slow").text("Guess a letter: ");
guessLetter();
}
} // end play function
function guessLetter() {
var showLetter;
guess++
console.log(guess); //SHOWS THE COUNTER ADDING UP CONTINUOUSLY AFTER 2
$("#alphabet li").on('click', function () {
$(this).css("visibility", "hidden");
x = this.id;
if (city.indexOf(x) == -1) {
$prompt.fadeIn("slow").text("No letter " + x);
setTimeout(play, 1500);
} else {
for (i = 0; i < length; i++) {
if (city[i] == x) {
$prompt.fadeIn("slow").text("There is letter " + x + "!");
showLetter = "#showCity li:nth-child("+(i+1)+")";
$(showLetter).css("color", "#0F9ED8");
}
} //for loop
setTimeout(play, 1500);
} //else
});
}
function ending(){ //STILL IN PROGRESS
var guessWord,
finalOutput;
$prompt.fadeIn("slow").text("What is the word? ");
//guessWord = word from input
finalOutput = (guessWord == city) ? "That is correct!" : "Sorry, that is wrong.";
$prompt.fadeIn("slow").text(finalOutput);
}
$(document).ready(function(){
$("#start").on('click', function() {
$(this).hide();
randomCity();
console.log(city);
$("#alphabet").css("visibility", "visible");
play();
});
}); // end ready
variable guess (the counter) has value of 4 after clicking the 2nd element, and has a value of 6 after clicking the 3rd element. I moved the var guess in different parts of my code but it is still doing that. This is very weird!
By doing
$("#alphabet li").on('click', function () { /* ... */}`
you're binding a new click handler every time the guessLetter() function gets executed. Multiple click handlers will call the play() function which in turn calls the guessLetter() function again, resulting in guess being incremented multiple times.
Bind the click handler only once.
You are attaching a new click handler to your list items every time the guessLetter function is called.
To fix it, you could move everything in guessLetter which occurs after your console.log call into the $(document).ready callback function.

Add Class to div when click counter reaches 0

Right now when you click inside the div, the counter decreases by 1. How do I make it stop at 0?
Also when it reaches 0 how can I add a class?
I want the overlay to be enabled once the click counter reaches 0.
If there is a better way to disable the div box1 after the clicks reach 0. We can try it that way.
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) - 1 );
});
});
fiddle
Rather than searching DOM and parsing HTML on each click, I'd cache both element and its value:
var $box = $('#box1'),
$num = $box.find('.num'),
limit = $num.text();
$box.click(function() {
$num.text(--limit);
if (limit === 0) {
$('.overlay').show();
}
});
Demo.
This should do it:
$('.box').click( function() {
var num = $(this).find('.num');
val = parseInt(num.text()) - 1;
if (val > 0){
num.text(val - 1);
} else {
$(".overlay").show();
// add your class here.
}
num.text( val );
});
Updated Fiddle

How to increase and decrease a counter from one button - click and click again jQuery

This is the code that I am currently using:
<script>
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1+1 });
});
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1-1 });
});
</script>
When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?
You can use an external var to decide if you have to increment o decrement the value
<script>
var increment = true;
$(".lk").click(function(){
var lke = $(this).find("#lke"),
value = parseInt(lke.html()) || 0;
lke.html( increment ? value + 1 : value - 1);
increment = !increment;
});
</script>
Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.
You could use an external variable such as toAdd to determine which action to do:
var toAdd = 1;
$(".lk").click(function(){
newValue = oldValue + toAdd;
toAdd *= -1;
...
});
You put two call of the same object, try this instead
<script>
var val = 0; // Put the original value
var negative = false;
$( document ).ready(function() { // You need to declare document ready
$(".lk").click(function(){
val = val + ((negative) ? -1 : 1); // Change if its positive or negative
negative = (negative) ? false : true;
$("#lke").text(val); // Adjust the html ?
});
});
</script>
Try something like this:
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).removeClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).addClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});
You could also use a data attribute instead of checking for a class aswell.
Or use toggleClass().
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).toggleClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).toggleClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});

For loop using jQuery and JavaScript

I'm trying to do a simple for loop in JavaScript/jQuery
every time I click NEXT, I want the I to increment once.
But it is not working. When I press next, nothing happens.
<script>
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
//start increment with 0, until it is reach 5, and increment by 1
for (var i=0; i < 5 ;i++)
{
//when I click next field, run this function
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
var fields_box = '#field_'+[i];
show_form_field(fields_box)
})
}
});
</script>
You do not need the for loop. Just declare var i outside click function and increment it inside the function.
//function to show form
function show_form_field(product_field) {
$(product_field).show("slow");
}
$(document).ready(function () {
var i = 0; // declaring i
$("#next_field").click(function () {
if (i <= 5) { // Checking whether i has reached value 5
var fields_box = '#field_' + i;
show_form_field(fields_box);
i++; // incrementing value of i
}else{
return false; // do what you want if i has reached 5
}
});
});
You should declare variable i document wide, not inside the click handler.
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
var i=0;
$("#next_field").click(function(){
var fields_box = '#field_'+ i++ ;
show_form_field(fields_box)
})
});
Call $("#next_field").click just one time, and in the click function, increase i every time.
$(document).ready(function() {
var i = 0;
$("#next_field").click(function() {
if (i >= 5) {
//the last one, no more next
return;
}
show_form_field('#field_' + (i++));
});
});
try this
$(document).ready(function(){
//start increment with 0, untill it is reach 5, and increment by 1
var i = 0;
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
if(i<5)
{
var fields_box = '#field_'+i;
show_form_field(fields_box);
i+=1;
}
else
{
return;
}
});
});

FadeIn multiples of 6 divs at a time with click

I have this code below that basically gets a number of elements and stops them at 6 items. I have then got a button that when clicked loads in remaining divs.
I just want it to load in 6 divs at a time. Does anyone know the way forward to do this at all?
Here is the javascript:
function click_load() {
var count = 0;
var item = $('.newsmainimages');
//var itemClick = $('Load More');
$(item).each(function() {
if (++count == 6) {
$(this).parent().append('<div class="nextClick">Load More</div>');
}
else if (count > 6) {
$(this).css('display','none');
}
});
$('.nextClick a').click(function() {
$(item).each(function(item) {
$(this).delay(200*item).fadeIn("slow");
});
alert(item);
return false;
});
}
Cheers
You can use slice for this kind of things
DEMO
$(function(){
var count = 6;
showListItems(0 , count);
$('button').click(function() {
showListItems(0, ($('ul li:visible').length) + count);
});
function showListItems(firstNumber, lastNumber)
{
$('ul li').slice(firstNumber, lastNumber).fadeIn("slow");
}
});​

Categories