How to make disabled button after some amount of clicks - javascript

I have tried to disable my button once the user has clicked a button three times, using the following code:
var count = 0;
function clickFunc() {
count += 1;
var click = document.getElementById('clicks').innerHTML = count;
var btn = document.querySelector('.btn');
}
if(count >= 3) {
btn.disabled = true;
}
Why is my btn.disabled = true; statement never executed?

By moving the if statement inside the clickFunc(), it will be called every time the button is clicked and check it at that time. When writing code, try to run through it in your mind. If statements should be placed where they make the most logical sense.
var count = 0;
function clickFunc() {
count += 1;
var click = document.getElementById('clicks').innerHTML = count;
var btn = document.querySelector('.btn');
if(count >= 3)
btn.disabled = true;
}

var count = 0;
function clickFunc() {
count += 1;
var click = document.getElementById('clicks').innerHTML = count;
var btn = document.querySelector('.btn');
if(count >= 3) {
btn.disabled = true;
}
}
clickFunc();
clickFunc();
clickFunc();
In the third call it will be disabled.

Here is a quick example.
$(document).ready(function() {
var count=0;
//called when button is clicked.
function clickFunc() {
count += 1;
//lets say id of button is btn
if(count>3){
$('#btn').prop('disabled', true);
}
}
});
or you can just move the if statement inside the function.
Hope that was any helpful!

var count = 0;
function clickFunc() {
count += 1;
var click = document.getElementById('clicks').innerHTML = count;
var btn = document.querySelector('.btn');
if(count >= 3) { // placed inside the click function
btn.disabled = true;
}
}
<div id="clicks">0</div>
<br/>
<button class="btn" onclick="clickFunc()">Click Me</button>

Would you like to use it as a simple module? Are you using jQuery?
HTML
<body>
<button>Click!</button>
</body>
JS
var myCounter= (function() {
var clicksleft= 3;
var startCount= function(onFinish) {
var me= this;
clicksleft = clicksleft - 1;
if(clicksleft===0) {
onFinish();
}
};
return {
startCount: startCount
}
})();
jQuery(function ($) {
$('button').click(function() {
myCounter.startCount(function() {
$('button').attr('disabled','disabled');
});
});
});

<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(function(){
var count = 3,
$btn = $('input[type="submit"]'); //Or which ever you want
//Change the label of $btn
$btn.val($btn.val()+' ('+count+')')
$btn.click(function(){
$btn.val($btn.val().replace(count,count-1));
count--;
if(count==0) {
return !$btn.attr('disabled','disabled');
}
})
})
</script>
<title>Javascript</title>
</head>
<body>
<input type="submit" value="Test">
</body>
</html>

Related

Redirect to another page after mouse counter [duplicate]

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
Closed 12 months ago.
I want to redirect to another page if counter > 5.
Can you please help me?
This is my code:
<p class="times">
<span id="display">0</span>
</p>
<script type="text/javascript">
var count = 0;
var disp = 0;
var btn = document.getElementById("btn");
var disp = document.getElementById("display");
btn.onclick = function () {
count ++;
disp.innerHTML = count;
}
</script>
You can do that with location.href = "".
<p class="times">
<span id="display">0</span>
</p>
<script type="text/javascript">
var count = 0;
var disp = 0;
var btn = document.getElementById("btn");
var disp = document.getElementById("display");
btn.onclick = function () {
count ++;
disp.innerHTML = count;
if (count > 5) {
location.href = "https://google.com/";
}
}
</script>
btn.onclick = function () {
count ++;
disp.innerHTML = count;
if(count > 5) {
//this will change the location of the window object aka. redirect
window.location.href = 'http://my_addreess.com';
}
}
<p class="times">
<span
id="display">0</span>
</p>
<button id='btn'>click</button>
<script type="text/javascript">
var count = 0;
var disp = 0;
var btn = document.getElementById("btn");
var disp = document.getElementById("display");
btn.onclick = function () {
count ++;
disp.innerHTML = count;
if (count == 5)window.location.href="https://www.stackoverflow.com"
}
</script>

Restrict counter to be between 0 and 10

I would like to create 2 buttons one of which increases a number and the other decreases it, and I did do it. The problem is I don't want the numbers to go higher than 10 or lower than 0, I tried if else but didn't work. Can you, please, help me?
Here is the code:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#add').onclick = adding
document.querySelector('#minus').onclick = subtracting
})
let counter = 0
function adding() {
counter++
document.querySelector('h1').innerHTML = counter
}
function subtracting() {
counter--
document.querySelector('h1').innerHTML = counter
if( counter < 1){
document.getElementById('minus').disabled = true
} else{
document.getElementById('minus').disabled = false
}
}
I recommend you delegate and use booleans in the way they are meant
I disabled the minus on load
window.addEventListener("load", function() {
let counter = 0;
const plus = document.getElementById('plus');
const minus = document.getElementById('minus');
const result = document.querySelector('h1');
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
counter += tgt.id === "plus" ? 1 : -1; // which one did we click - this can be expanded
minus.disabled = counter < 1;
plus.disabled = counter >= 10;
result.innerHTML = counter;
})
})
<div id="container">
<button type="button" id="minus" disabled>-</button>
<h1>0</h1>
<button type="button" id="plus">+</button>
</div>
One way is
const MAX_COUNTER = 10;
const MIN_COUNTER = 0;
function adding() {
if (counter < MAX_COUNTER) {
counter++
document.querySelector('h1').innerHTML = counter
}
}
Another way is:
const MAX_COUNTER = 10;
const MIN_COUNTER = 0;
function adding() {
counter = Math.min(counter + 1, MAX_COUNTER);
document.querySelector('h1').innerHTML = counter
}
The subtracting is similar.
Your code works fine. You only need to add another if conditional for adding and put it in the adding function.
if( counter >=10){
document.getElementById('add').disabled = true
} else{
document.getElementById('add').disabled = false
}
I added a working snippet for you, you can create a common function to set the value andenable or disable button based on counter values.
var counter = 0;
document.addEventListener("DOMContentLoaded", function() {
//initial value
setCounterValue(counter);
//add function
document.querySelector('#add').onclick = function() {
setCounterValue(++counter); //increase the counter
}
//substract function
document.querySelector('#minus').onclick = function() {
setCounterValue(--counter); //decrease the counter
}
});
//set the value and enable or disable buttons
function setCounterValue(value) {
document.querySelector('h1').innerHTML = value;
document.getElementById('minus').disabled = (value <= 0);
document.getElementById('add').disabled = (value >= 10);
}
<p> Counter </p>
<h1 id="h1"> </h1>
<button id="add">Add</button> <button id="minus">Substract</button>

Have a script that changes div after time interval need to alter so it only runs once

I have the following js that changes div content at a time interval, I love how it works but need to alter it so script only runs once how do I do this?
<script type="text/javascript">
function initChangeText()
{
var time = 10;
setInterval('changeText();',time*1000);
}
function changeText()
{
var divs_ = document.getElementsByTagName("div")
for (var i = 0;i<divs_.length;i++)
if (divs_[i].className == "change")
changeULText(divs_[i]);
}
function changeULText(obj)
{
var ul = obj.getElementsByTagName("ul")[0];
var li = obj.getElementsByTagName("li");
for (var i=0;i<li.length;i++)
{
if (li[i].className == "show")
{
li[i].className = "";
li[(i+1)%li.length].className = "show";
return ;
}
}
}
window.onload = initChangeText;
</script>
Thanks
Tim
You can use setTimeout instead of setInterval
function initChangeText(){
var time = 10;
setTimeout(changeText,time*1000);
}
function changeText(){
var divs_ = document.getElementsByTagName("div")
for (var i = 0;i<divs_.length;i++)
if (divs_[i].className == "change")
changeULText(divs_[i]);
}
function changeULText(obj) {
var ul = obj.getElementsByTagName("ul")[0];
var li = obj.getElementsByTagName("li");
for (var i=0;i<li.length;i++){
if (li[i].className == "show"){
li[i].className = "";
li[(i+1)%li.length].className = "show";
return ;
}
}
}
window.onload = initChangeText;
</script>

Javascript/HTML button click error

I am using JavaScript with my html page to try an get a button to show a message to the user, but when I click the button, nothing happens. Is there something I am doing wrong?
<input type="button" name="get" id="getmsg" value="Get Message"/>
<script type="text/javascript">
document.getElementById("getmsg").onclick = msgtouser;
function (msgtouser)
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
</script>
That is not how you define a function
function (msgtouser)
should be
function msgtouser ()
Try on this way:
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i << 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
Note function msgtouser() instead function (msgtouser).
Here are some of the points which you need to correct:
function (msgtouser) should be function msgtouser ()
Use window.load or .ready() function.
My guess is you are trying to generate random number between 1 and 012345 i.e topick.length,if so then remove that outer array topick[].
Here is a working code:
window.onload=function(){
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += Math.floor((Math.random()*topick.length)+1);
}
alert(msg);
}
}

javascript clear timeouts in loop

The code below appends numbers in sequence from 1 to 10 when the start button is clicked. I'd like to use clearTimeout to cancel the operation when the stop button is clicked.
It seems to me that a dynamic variable must be created (where x is currently assigned the doSetTimeout function), but I have not yet found a way to do so. Any suggestions?
Thanks!
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function doSetTimeout(func, func_param, time) {
setTimeout(function(){func(func_param);}, time);
}
function createNode(base) {
var node = document.createElement("p");
var writeI = base + "";
var textnode = document.createTextNode(writeI);
node.appendChild(textnode);
document.body.appendChild(node);
}
$(document).ready(function() {
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
var x = doSetTimeout(createNode, i, time);
}
});
});
</script>
</head>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
Get the return value of setTimeout, keep it in a list, and clear it when you click stop.
function doSetTimeout(func, func_param, time) {
return setTimeout(function(){func(func_param);}, time);
}
$(document).ready(function() {
var timeouts = [];
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
timeouts.push(doSetTimeout(createNode, i, time));
}
});
$("#stop").click(function () {
for (var i = 0; i <= timeouts.length; i += 1) {
clearTimeout(timeouts[i]);
}
});
});
This might also clear timeouts that have already finished, but I doubt that's really very important.

Categories

Resources