I try to change a button text after click for a few seconds. On the page are buttons dynamically build by a PHP database while loop. Every button gets an id dynamically like button0, button1, button2 etc.....
echo "<a href='rdp://" . $record["ip_adress"] . "'><button id='button".$counter."' type='button' class='button' onclick=\"btn('button".$counter."')\" style='vertical-align:middle'"?>
<?php if($freeusers == 0){echo "disabled>No Login";}else{echo ">Login";}?> <?php echo "</button></a>";
And here the Javascript Code:
<script>
function btn(i){
document.getElementById(i).addEventListener('click', function (clicked) {
return function () {
if (!clicked) {
var last = this.innerHTML;
this.innerHTML = 'please wait...';
clicked = true;
setTimeout(function () {
this.innerHTML = last;
clicked = false;
}.bind(this), 5000);
}
};
}(false), this);
}
</script>
The Button name passes through the function after click. But the programm never reached after if(!clicked){ ... It seems, that it not recognizing a "click" or something. But I dont know what to do.
Greetings
CodePudding user response:
You could try something like this. Assign the event listener to the hyperlink and use this
within the event handler to find the button
and modify it's properties
document.querySelectorAll('a[href^="rdp:"]').forEach(a => {
bttn = a.firstElementChild;
bttn.dataset.alt = 'Please wait...';
bttn.dataset.value = bttn.innerHTML;
a.addEventListener('click', function(e) {
let bttn = this.firstElementChild
bttn.innerHTML = bttn.dataset.alt;
setTimeout(() => {
bttn.innerHTML = bttn.dataset.value;
}, 5000)
});
});
<a href="rdp:192.168.0.4" target="_blank">
<button type="button" >Login</button>
</a>
<a href="rdp:192.168.0.57" target="_blank">
<button type="button" >Login</button>
</a>
CodePudding user response:
Here is your working solution
document.getElementById('i').addEventListener('click', function () {
var btnText = this.innerText;
this.innerText = 'Please Wait...';
setTimeout(function () {
document.getElementById('i').innerText = btnText;
}, 1000);
})
replace this with selector on setTimeout method
CodePudding user response:
I would take a different approach. For example you can add a class to those buttons - and simply loop them. You can then add the logic for each button by adding a event listener
const myButtons = document.querySelectorAll('.my-button')
for (let i=0; i <= myButtons.length; i ) {
myButtons[i].addEventListener('click', e => {
...
})
}
You also might want to include an async attribute on your script tag. That way you can be sure that the HTML doesn't load after the script.
<script async ...>