I am having trouble with resetting the counter in jquery (clickfunction) - javascript

I am trying to repeat the clickfunction but it will only repeat twice. After that the counter disappears. I don't know what the cause of this is. H
var divClone = $("#target").clone();
var divClone = $("#output").clone();
var clickCount = 0;
$('#target').click(function() {
if ( clickCount < 6){
clickCount++;
$('#output').html(function(i, val) { return val*1+1 });
} else {
clickCount = 0;
$("#output").replaceWith(divClone);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target" type="button">Click Me</button>
<div id="output">0</div>
Note that I am quite new to programming.
Thanks in advance.
Edit: Sorry, I don't want it to be automatic. After every 6 clicks the counter should reset to zero.

Try this
http://jsfiddle.net/zRX2D/2707/
var clickCount = 0;
$('#target').click(function() {
if ( clickCount < 6){
clickCount++;
} else {
clickCount = 0;
}
$('#output').html(clickCount);
});

Try this:
var clickCount = 0;
$('#target').click(function() {
if (clickCount++ < 6) {
$('#output').html(function(i, val) {
return val * 1 + 1
});
} else {
clickCount = 0;
$('#output').html('0');
}
});
Demo: https://jsfiddle.net/tusharj/zRX2D/2708/
OR
Simple:
var clickCount = 0;
$('#target').click(function () {
$('#output').html(++clickCount % 7);
});
Demo: https://jsfiddle.net/tusharj/zRX2D/2711/

Check following:
var clickCount = 0;
$('#target').click(function() {
clickCount = clickCount < 6 ? clickCount+=1 : 0;
$("#output").text(clickCount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target" type="button">Click Me</button>
<div id="output">0</div>

Related

how to add input value to counter value?

I'm trying to have a counter that can respond to input values and add it to displayed count but continue to count by 1. The count starts at 0. I have the counter working with buttons, but not with the added input.
let decreaseBtn = document.getElementById("buttonDecrease");
let increaseBtn = document.getElementById("buttonIncrease");
let counter = document.getElementById("counter");
let inputValue = document.getElementById("quantity").inputValue
let count = 0;
decreaseBtn.addEventListener("click", () => {
count--;
counter.innerHTML = count;
counterStyle();
});
increaseBtn.addEventListener("click", () => {
count++;
counter.innerHTML = count;
counterStyle();
});
function counterStyle() {
if (count < 0) {
counter.classList.add("negative");
} else if (count > 0) {
counter.classList.add("positive");
} else {
counter.classList.remove("negative");
counter.classList.remove("positive");
}
}
function addInput() {
console.log(inputValue)
}
addInput();
<h1 id="counter">0</h1>
<div id="button__wrapper">
<button id="buttonDecrease">-</button>
<input type="text" id="quantity" value="1">
<button id="buttonIncrease">+</button>
</div>
Yuo need to get the value of the input in your event listener functions, not when the script starts. Then use that instead of just incrementing and decrementing.
The property to get the value of an input is .value, not .inputValue.
let decreaseBtn = document.getElementById("buttonDecrease");
let increaseBtn = document.getElementById("buttonIncrease");
let counter = document.getElementById("counter");
let quantity = document.getElementById("quantity");
let count = 0;
decreaseBtn.addEventListener("click", () => {
count -= addInput();
counter.innerHTML = count;
counterStyle();
});
increaseBtn.addEventListener("click", () => {
count += addInput();
counter.innerHTML = count;
counterStyle();
});
function counterStyle() {
if (count < 0) {
counter.classList.add("negative");
counter.classList.remove("positive");
} else if (count > 0) {
counter.classList.add("positive");
counter.classList.remove("negative");
} else {
counter.classList.remove("negative");
counter.classList.remove("positive");
}
}
function addInput() {
return parseInt(quantity.value);
}
.positive {
background-color: green;
}
.negative {
background-color: red;
}
<h1 id="counter">0</h1>
<div id="button__wrapper">
<button id="buttonDecrease">-</button>
<input type="text" id="quantity" value="1">
<button id="buttonIncrease">+</button>
</div>
You have increment and decrement operators when you handle the click event. This is why it is always just adding or subtracting by 1, and not by the value of the input. You should be adding the value of the input element, after using parseInt() to make it into an add-able integer.
Your code that I'm changing:
count--;
What I'm changing it to...
count -= parseInt(document.getElementById('quantity').value, 10);
And I'm doing the same for count++.
In addition, it seems your counterStyles() function isn't removing classes appropriately, and sometimes you'll have a red background with positive integers. I fixed this up by adding the needed removeClass() calls here.
The rest of the code is the same...
let decreaseBtn = document.getElementById("buttonDecrease");
let increaseBtn = document.getElementById("buttonIncrease");
let counter = document.getElementById("counter");
let inputValue = document.getElementById("quantity").inputValue
let count = 0;
decreaseBtn.addEventListener("click", () => {
count -= parseInt(document.getElementById('quantity').value, 10);
counter.innerHTML = count;
counterStyle();
});
increaseBtn.addEventListener("click", () => {
count += parseInt(document.getElementById('quantity').value, 10);
counter.innerHTML = count;
counterStyle();
});
function counterStyle() {
if (count < 0) {
counter.classList.add("negative");
counter.classList.remove("positive");
} else if (count > 0) {
counter.classList.add("positive");
counter.classList.remove("negative");
} else {
counter.classList.remove("negative");
counter.classList.remove("positive");
}
}
function addInput() {
console.log(inputValue)
}
addInput();
.positive {
background-color: green;
}
.negative {
background-color: red;
}
<h1 id="counter">0</h1>
<div id="button__wrapper">
<button id="buttonDecrease">-</button>
<input type="text" id="quantity" value="1">
<button id="buttonIncrease">+</button>
</div>

JavaScript not further executed once a button is disabled

I am using next and prev buttons so one question will be shown at a time, however, once next or prev buttons are disabled, the other button doesn't work anymore either. Here's my code:
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("next").disabled = true;
} else {
console.log(i);
qElems[i + 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i + 1] = 1;
}
break;
}
}
}
function prev() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 4) {
document.getElementById("prev").disabled = true;
} else {
qElems[i - 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i - 1] = 1;
}
break;
}
}
}
I think you want this simplified script
I had to guess the HTML, but there is only one function.
window.addEventListener("load", function() {
let showing = 0;
const questions = document.querySelectorAll(".q");
questions[showing].style.display = "block";
const next = document.getElementById("next");
const prev = document.getElementById("prev");
document.getElementById("nav").addEventListener("click", function(e) {
var but = e.target, dir;
if (but.id === "prev") dir = -1;
else if (but.id === "next") dir = 1;
else return; // not a button
questions[showing].style.display = "none"; // hide current
showing += dir; // up or down
next.disabled = showing === questions.length-1;
if (showing <= 0) showing = 0;
prev.disabled = showing === 0
questions[showing].style.display = "block";
})
})
.q { display:none }
<div class="q" id="q0">Question 0</div>
<hr/>
<div class="q" id="q1">Question 1</div>
<hr/>
<div class="q" id="q2">Question 2</div>
<hr/>
<div class="q" id="q3">Question 3</div>
<hr/>
<div id="nav">
<button type="button" id="prev" disabled>Prev</button>
<button type="button" id="next">Next</button>
</div>
Since this is a quiet interesting java script task, Im doing my own solution.
Hope this matches the requirement.
I have created 4 divs of which first one is only displayed at first. Remaining divs are placed hidden. On clicking next, the divs are displayed according to index. Once the last and first indexes are interpreted, the respective next and previous buttons are enabled and disabled.
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
var qElems = [];
function initialize() {
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
}
function updatevisibilitystatus(showindex, hideindex) {
qElems[showindex].style.display = 'block';
qElems[hideindex].style.display = 'none';
showing[showindex] = 1;
}
function next() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 2) {
document.getElementById("next").disabled = true;
}
updatevisibilitystatus(i + 1, i);
document.getElementById("prev").disabled = false;
break;
}
}
}
function prev() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == 1) {
document.getElementById("prev").disabled = true;
}
updatevisibilitystatus(i - 1, i);
document.getElementById("next").disabled = false;
break;
}
}
}
<body onload="initialize()">
<div id="q0" style="display: block;">Q0</div>
<div id="q1" style="display: none;">Q1</div>
<div id="q2" style="display: none;">Q2</div>
<div id="q3" style="display: none;">Q3</div>
<button id="prev" disabled onclick="prev()">Prev</button>
<button id="next" onclick="next()">Next</button>
</body>

The image changes automatically - Start button

I wanted to add a button to start the change between images, to avoid the start of the change on its own
You must press the button until the change starts
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
Hi Please have a look I hope it's helpful Thanks
https://jsfiddle.net/sanat/xc5w8ngy/7/
<button id="start">
start
</button>
<button id="stop">
stop
</button>
<br>
<br>
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
var myVar = '';
$(function(){
$("#start").on('click',function(){
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
myVar = setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
});
$("#stop").on('click',function(){
clearInterval(myVar);
});
});

javascript disable button conditionally

How come I get the alert's but the button doesn't enable after a negative is changed to a positive after updating the grand total from a select.
Here is the section that is not working:
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
and here is the complete code:
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
});
</script>
Any ideas would be appreciated.
UPDATE
Here is the html for the Grand total:
<input type="text" class="grand_total" name="grand_total" id="grand_total" data-role="none" value="0" size="3" readonly="true">
and here is the button which i'm trying to disable:
<button type="submit" data-theme="e" data-mini="true" data-inline="true" name="submit" id="submit" class="submit" data-icon="check" value="submit-value">Submit</button>
With Nick N's suggestion, still get the same problem with the button disable/enable.
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
//if (parseFloat($('.grand_total').val()) < 0) {
// $('#submit').prop('disabled', true);
// alert('negative number found');
//} else if (parseFloat($('.grand_total').val()) > 0) {
// $('#submit').prop('disabled', false);
// alert('positive number found');
//}
var total = parseFloat($('#grand_total').val());
if(total < 0){
$('#submit').prop('disabled', true);
alert('negative number found...');
}
else {
$('#submit').prop('disabled', false);
alert('positive number found...');
}
});
</script>
UPDATE
Ok looks like the issue is because the button is a jquery mobile generated button its not updating the state of the button when a negative value is found, If i refresh the whole form the button state then chnages. I tested this by setting the data-role to none so the submit button becomes a standard form button and the disable/enable functionality works.
Any ideas how i can get around this?
This should work:
var total = parseFloat($('.grand_total').val());
if(total < 0){
$('#submit').attr("disabled", "disabled");
alert('negative number found');
}
else {
$('#submit').removeAttr("disabled");
alert('positive number found');
}
Jquery Mobile: Don't refresh the whole form, but refresh just the button:
$('#submit').button('refresh');
Please note: that I changed '#' to '.'. Dependent on your HTML you could also change this line:
$(".grand_total").val(grand_total);
to:
$("#grand_total").val(grand_total);
you are passing $('.grand_total').val()
instead of $('#grand_total').val()
try this:
var total = parseInt($('.grand_total').val());
if(total < 0){}
else {}

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Categories

Resources