Disable button with javascript - javascript

I have a button. The button works fine. After I have pressed the button, then it shall not be possible to press the button again. It will be best if the button looks diabled.
I have already tried with document.getElementById("id").disabled = true; but I can't make this work.
PHP code for the button. The code makes a list of buttons. Each button has id= 1, 2, 3 etc.
if($_COOKIE["sorterdb"]=='GR' || empty($_COOKIE["sorterdb"])){$dblinjer[$i]['nrlink']='<span id="para'.$i.'"></span><div class="s-12 l-12"><button type="button" id="'.$i.'" value="'.$dblinjer[$i]['loebid'].'_'.$dblinjer[$i]['tid'].'_'.$dblinjer[$i]['utcstart'].'" onclick=baadimaal("baadimaal",this)>'.$dblinjer[$i]['buttonnrsejl'].'</button></div>';}
javascript:
function baadimaal(str,el) {
var x = el.value
var id = el.getAttribute("id")
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("container"+id).innerHTML = this.responseText; //her placeres svaret, som kommer tilbage fra hide-ajax-svar filen
}
xhttp.open("GET", "hide-ajax-svar.php?funk=" + str + "&para=" + x + "&i=" + id); //overfør str og x til hide-ajax-svar filen
xhttp.send();
}

You can set the button's disabled property to false (see Sütemény András's answer), but that may not work in all browsers. You can also remove the listener, however that doesn't make the button look disabled.
So a belt and braces approach is to do both, e.g.
window.onload = function() {
// Listener
function clickFn() {
console.log('I\'ve been clicked! But no more…');
// Make button appear disabled
this.disabled = true;
// Remove the listener
this.removeEventListener('click', clickFn);
}
// Add the listener to the button
document.getElementById('b0').addEventListener('click', clickFn, false);
};
<button id="b0">Click me</button>
Note that if using setAttribute as in:
button.setAttribute('disabled', true);
the second argument is required but its value is irrelevant (it can be false, 'foo bar', 42, whatever). Regardless of the value, the element will be disabled, which is a hangover from ancient times when boolean attributes were added to HTML. Their presence alone does the job, they don't take a value (e.g. <button disabled>foo</button> creates a disabled button).
To unset the attribute (i.e. to enable the button again), use removeAttribute.

If you have a button like this:
<button class="button" id="1">Button 1</button>
<button class="button" id="2">Button 2</button>
<button class="button" id="3">Button 3</button>
You can add javascript eventlistener, do the job, than disable:
const buttons = document.querySelectorAll(".button")
buttons.forEach((item) => {
item.addEventListener("click", ()=>{
// DO SOMETHING WHITH YOUR BUTTON
console.log(`You've clicked on ${item.id} and now I'm gonna disable it.`)
// disable
item.disabled = true;
})
})
And depending on your code, maybe you should add "removeEventListener" on your button.

Related

Can't change an element's innerText inside a callback

I'm trying to build a dynamic "reset" button which changes its innerText twice, in a loop: once when first clicked (changing from "Reset" to "Are you sure?") and once when clicked again (changing from "Are you sure?" to "Reset"). However, I can't get to modify the innerText inside the callback. It seems like I can modify the innerText just fine from the DOM console, so I assume that there's something that I don't know yet in terms of how event callbacks work in JS, and I can't figure out what it is.
function show_confirm_button() {
document.getElementById('reset-button').innerText = "Are you sure?";
document.getElementById('reset-button').onclick = reset_button;
}
function reset_button() {
/* resetting things here */
document.getElementById('reset-button').innerText = "Reset";
document.getElementById('reset-button').onclick = show_confirm_button;
}
show_confirm_button() is used in a simple bootstrap button:
<button class="..." type="button" onclick=show_confirm_button()>
<span id="reset-button">Reset</span>
</button>
What am I missing?
As #Barmar said:
You should be changing the onclick of the button, NOT the span.
This should work:
function show_confirm_button() {
document.getElementById('reset-button-text').innerText = "Are you sure?";
document.getElementById('reset-button').onclick = reset_button;
}
function reset_button() {
/* resetting things here */
document.getElementById('reset-button-text').innerText = "Reset";
document.getElementById('reset-button').onclick = show_confirm_button;
}
<button class="..." type="button" onclick=show_confirm_button() id="reset-button">
<span id="reset-button-text">Reset</span>
</button>

How to trigger alert function on button press?

I have a function that triggers an alert at a given time:
function breakTime() { // <<< do not edit or remove this line!
/* Set Break Hour in 24hr Notation */
var breakHour = 11
/* Set Break Minute */
var breakMinute = 47
/* Set Break Message */
var breakMessage = "Reports! Take Your Break!"
///////////////////No Need to Edit//////////////
var theDate = new Date()
if (Math.abs(theDate.getHours()) == breakHour && Math.abs(theDate.getMinutes()) == breakMinute) {
this.focus();
clearInterval(breakInt)
alert(breakMessage)
}
}
var breakInt = setInterval("breakTime()", 1000)
I want to assign this function to a button, so when the button is pressed, at an interval of 10 seconds after button press, the alert shows up to everyone that has access to the page. Is there any way to do it?
Note: the pop up alert is triggered without the button, but every one of my attempts to make a button that triggers the function doesn't trigger the pop up on every one's PC.
using just javascript:
<button id='buttonID'>Click Me</button>
function test() {
alert('break time!');
}
document.getElementById('buttonID').onclick = test;
// no () on test, otherwise it runs immediately.
https://jsfiddle.net/axq0ks6b/
HOWEVER this will only work locally on your page. If you want to press a button and send a prompt to everyone who has the page open, then you will need to set up server side scripts.
You can assign function on button click like
<input id='btn' type='button' onclick='breakTime();' >Click</input>
OR You can fire event on click
<input id='btn' type='button' >Click</input>
<script>
$(document).ready(function(){
$('#btn').onclick(funcion(){
breakTime();
});
})
</script>

Bind button to a Javascript case/action

I am new to Javascript, and i run into some big problems. I got some functions, which I can type into a text field and press enter, and the functions works. But i have created 4 buttons, which i want to connect to the actions.. i got 4 actions: "UP","DOWN","LEFT" and "RIGHT".
This is the js fiddle over my code: http://jsfiddle.net/n24gQ/
I have made the buttons like this but I dont know what to write inside the OnClick tag?
<div id="gamebuttons">
<button id="up" button onClick="">UP</button>
<button id="down" button onClick="">DOWN</button>
<button id="left" button onClick="">LEFT</button>
<button id="right" button onClick="">RIGHT</button>
</div>
I hope you can understand what my problem is. I made 4 javascript cases which I want to bind to 4 html buttons if possible.. :) It is the cases: "frem" "tilbage" "hoejre" and "venstre" i need to bind.. Sorry not everything in the code is english, but it should be understandable..
Fiddle
You can simply write the function name you've defined for the buttons into the onclick attribute, e.g. like this:
<button id="up" type="button" onclick="alert('UP'); return false;">UP</button>
However, as your buttons already have id's you can also check if one of those id's got clicked without the need of onclick in your markup:
JavaScript:
var buttonUp = document.getElementById('up');
buttonUp.onclick = function() { myFunction(); return false; }
jQuery:
$('#up').on('click', myFunction());
Instead of using inline handlers (bad practice) or multiple handlers for each button, I would use event delegation on your button wrapper, like so
$('#gamebuttons').on('click', 'button', function() {
/* get the id attribute of the clicked button */
var button_id = this.id;
case (button_id) {
"UP" : /* code for up button */ break;
"DOWN" : /* code for down button */ break;
"LEFT" : /* code for left button */ break;
"RIGHT" : /* code for right button */ break;
}
});
Please pass the function name inside the OnClick tag
for example if you want to associate playGame function to DOWN button
write
<button id="down" onclick="playGame();">DOWN</button>
I think these below changes will give you solution.
Instead of the first button, you need to bind events to all of the buttons which you required. Currently, querySelector() getting only first button to bind events. So, use querySelectorAll()
Replace this code
var button = document.querySelector("button");
button.style.cursor = "pointer";
button.addEventListener("click", clickHandler, false);
button.addEventListener("mousedown", mousedownHandler, false);
button.addEventListener("mouseout", mouseoutHandler, false);
With below code
var gamebuttonslist=document.querySelectorAll("#gamebuttons button");
for (var vitem=0;vitem<gamebuttonslist.length;vitem++) {
if (typeof gamebuttonslist[vitem] != "undefined" && gamebuttonslist[vitem] != null) {
gamebuttonslist[vitem].style.cursor = "pointer";
gamebuttonslist[vitem].addEventListener("click", clickHandler, false);
gamebuttonslist[vitem].addEventListener("mousedown", mousedownHandler, false);
gamebuttonslist[vitem].addEventListener("mouseout", mouseoutHandler, false);
}
}

Day/Night mode - CSS + JQuery - Cookies?

I'm testing javascript code for day/light background switch and I don't know how to do something. I'm newbie to javascript, so I'm learning new stuff.
So what I want to do?
When I click for example on button "Day" (which change background to yellow), I want that style for yellow background stay in the code after page is refreshed. I heard something about Cookies/LocalStorage, but I don't know how to implement it for this code.
Feel free to change whole code if you know easier way to do this, but please explain why it's better or why it should be like that.
Thanks in advance for your help.
Here is the code:
HTML:
<body id="body">
<input type="button" onclick="day();" value="Day" />
<input type="button" onclick="night();" value="Night" />
<input type="button" onclick="reset();" value="Reset" />
</body>
CSS:
.darkSwitch {
background: #808080;
}
.lightSwitch {
background: #ffff99;
}
JavaScript:
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function() {
var button = $('input[type=button]');
button.on('click', function() {
button.not(this).removeAttr('disabled');
$(this).attr('disabled', '');
});
});
Last edit: now disabling selected button on page load, CODE NOT IN THIS POST, see the latest JSFiddle
Explanation
What I did:
The code is put in between<script> tags at the end of the <body> (personnal preference)
I added the parameter event to the onClick event of the button element.
I added event.preventDefault() at the start of the onclick event of the button element: ensuring the page is NOT refreshed on the click of a button.
Warning: ALL the buttons will behave the same in your page. If you have other buttons, I suggest you add another class for those three buttons and bind the event on the button.myClass element.
I added a condition on the button state change, so the reset button won't get disabled.
eval($(this).val().toLowerCase()+"();"); gets the value of the the clicked button and executes the function attached to it.
Solution
HTML
<body id="body">
<input type="button" class="changeBg" onclick="day();" value="Day" />
<input type="button" class="changeBg" onclick="night();" value="Night" />
<input type="button" class="changeBg" onclick="reset();" value="Reset" />
</body>
JavaScript
(JSFiddle) <-- Check this out Updated with classes & cookies
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function () {
/* RegEx to grab the "bgColor" cookie */
var bgColor = document.cookie.replace(/(?:(?:^|.*;\s*)bgColor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var button = $('input[type=button].changeBg');
button.on('click', function (event) {
event.preventDefault();
/* Executing the function associated with the button */
eval($(this).val().toLowerCase() + "();");
button.not($(this)).removeAttr('disabled');
if ($(this).val() != "Reset") {
$(this).attr('disabled', '');
/* Here we create the cookie and set its value, does not happen if it's Reset which is fired. */
document.cookie = "bgColor="+$(this).val();
}
});
/* If the cookie is not empty on page load, execute the function of the same name */
if(bgColor.length > 0)
{
eval(bgColor.toLowerCase()+'()');
/* Disable the button associated with the function name */
$('button[value="'+bgColor+'"]').attr("disabled","disabled");
}
});
I recommend you don't use cookies unless localStorage is not supported. They slow your site down.
if(localStorage){
localStorage.setItem("bgColor", "lightSwitch");
}else{
document.cookie = "bgColor=lightSwitch";
}

Change onclick action with a Javascript function

I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear

Categories

Resources