javascript button disable and reenable after calculation doesn't work - javascript

My code is the following. When I click the search button, it enters a for loop that prints 5000 times "hi". Before this calculation begins, I want to disable the button. After the console.log is finished, I want to reenable this button. But for some reason, this isn't working. (To be more precise, although here I am simply printing logs, my actually work involves various calculations that take around 5 seconds to finish using for loops.)
$("#search").click(function() {
$("#search").prop("disabled",true);
$("#search").text("Loading...");
var i;
for(i = 0; i < 50000; i++)
console.log("hi");
$("#search").prop("disabled",false);
$("#search").text("Finished...");
});
https://jsfiddle.net/gs793zhx/

Try using .delay() with duration set to 1 , .queue() , .promise() , $.Deferred()
$("#search").click(function() {
$(this).prop("disabled", true)
.text("Loading...")
.css("color", "red")
.delay(1, "p")
.queue("p", function(next) {
next()
})
.dequeue("p")
.promise("p")
.then(function() {
var elem = this;
return $.Deferred(function(d) {
var i = 0, max = 50000;
for (;i < max; i++) {
console.log("hi");
}
if (i === max) {
d.resolveWith(elem, [i])
}
}).promise()
}).then(function(data) {
console.log(this, data);
$(this).prop("disabled", false)
.css("color", "blue")
.text("Finished...");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button type="button" id="search" class="btn btn-primary" style="width:100px; height:30px;">SEARCH</button>
jsfiddle https://jsfiddle.net/gs793zhx/1/

use $("#search").attr("disabled","disabled"); and $("#search").removeAttr("disabled"); instead

Problem is with browser's performance to log hi for 50000 times.
You may put logs into js variable and dump the variable once into the console.
var btn = $("#search");
btn.click(function() {
btn.prop("disabled", true);
btn.text("Loading...");
var log = [];
for (var i = 0; 50000 > i; i++)
log.push("i: " + i);
console.log(log);
btn.prop("disabled", false);
btn.text("Finished...");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='search'>Search</button>

$("#search").click(function() {
$("#search").prop("disabled",true);
$("#search").text("Loading...");
var i;
for(i = 0; i < 50000; i++) {
console.log("hi");
}
if(i==50000-1)
{
$("#search").prop("disabled",false);
$("#search").text("Finished...");
}
});

Related

can't access value through input using button

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

How to disable button after reaching condition in laravel

I am using laravel and stuck in a condition. i add counter and a condition that when counter equals to 4 disable the button and no more item added.
this is my code
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
var array = document.getElementsByClassName('compare');
for (var i = 0 ; i < array.length ; i++)
{
array[i].setAttribute('disabled','');
}
}
i want's to disable button after reaching the limit and no more item added from anywhere if the counter equals to 4.
var increment = 0;
$(document).ready(function() {
$(".compare").click(function() {
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" + increment + ")";
if (increment == 4) {
var array = document.getElementsByClassName('compare');
for (var i = 0; i < array.length; i++) {
array[i].setAttribute('disabled', '');
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="compare" id="compare">INCREMENT</button>
Not really Laravel related, but you don't need jQuery just to add a counter. Vanilla JS gets the job done:
<button id="btn" onclick="buttonCheck()">Click me</button>
<script>
var counter = 0;
function buttonCheck(){
counter++;
if (counter >= 4)
document.getElementById("btn").setAttribute("disabled", "disabled");
}
</script>
Seeing that you already have jQuery in your code. I'll give an example using jQuery.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").prop("disabled", true);
//prop() is used to set attribute value of an html element
}
}
}
Most of the time, this would work. But in some cases that it won't, you could manipulate this with CSS.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").css("pointer-events", "none");
}
}
}

Jquery code won't run loaded from footer, but run from console

I'm trying to get a value and pass it to a hidden input in order to send form data via $_POST. I have a dropdown button and the following code in order to update the value when a user select an option:
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
The code is supposed to pass the value from one button to another, as shown in here the example, but, when I load the code from WordPress header/footer/theme nothing happens. Instead, when I write it on the console it works fine. There are no JS errors in console.
Please note that I'm using .text() to test if the code works, but it would have .val() before going live.
This is the button HTML:
<button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="select-especialidad" title="Hacienda" aria-expanded="false"><span class="filter-option pull-left">Hacienda</span></button>
Here is an example: https://fiddle.jshell.net/t9mvoxj5/
EDIT TO INCLUDE THE FULL CODE:
( function( $ ) {
var num_cols = 3,
container = $('#menu-preparadores-de-oposiciones-en'),
listItem = 'li',
listClass = 'sub-list';
container.each(function() {
var items_per_col = new Array(),
items = $(this).find(listItem),
min_items_per_col = Math.floor(items.length / num_cols),
difference = items.length - (min_items_per_col * num_cols);
for (var i = 0; i < num_cols; i++) {
if (i < difference) {
items_per_col[i] = min_items_per_col + 1;
} else {
items_per_col[i] = min_items_per_col;
}
}
for (var i = 0; i < num_cols; i++) {
$(this).append($('<ul ></ul>').addClass(listClass));
for (var j = 0; j < items_per_col[i]; j++) {
var pointer = 0;
for (var k = 0; k < i; k++) {
pointer += items_per_col[k];
}
$(this).find('.' + listClass).last().append(items[j + pointer]);
}
}
});
if ($("body").hasClass("page-id-64")) {
$('.tab-content').addClass('col-sm-9');
$('#custom-tabs-0').tabCollapse();
}
} ) ( jQuery );
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
Well, the code is fine, the problem is that the target button[data-id="select-especialidad"] is being used by bootstrap-select and even if bootstrap-select loads before my code, it takes a few seconds (or at least a bit) to process the information.
So the code should be wrapped after a function that checks that the event has been loaded. This is the final code:
$('#select-especialidad').on('loaded.bs.select', function (e) {
var y = $(this).val();
$('#select-especialidad-hidden').val(y);
var espSeleccionada = $('button[data-id="select-especialidad"] > span.filter-option.pull-left');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#select-especialidad-hidden').val(x);
});
});
loaded.bs.select here more info on the bootstrap-select events.

How to make disabled button after some amount of clicks

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>

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