How can I disable a button in javascript? - javascript

I have a button which is enabled at the beginning, but I want to disable it. I need it for a game. If the player chooses to play more, the game starts again, if not, the button "Click on me" should be disabled. Thank you in advance!
Here is my code:
var y;
function playAgain()
{
y=confirm("PLAY AGAIN?");
if(y==true)
{
alert("Let's play it again!");
location.reload(true);
}
else if(y==false)
{
alert("Thank you!\nSee you soon!");
document.getElementById("button").disabled="disabled";
//document.getElementById("button").disabled="true";
}
}
The HTML code:
<body>
<input type="button" value="Click on me" onClick="playAgain()" />
</body>

This will work:
document.getElementById("button").disabled = true;
If your button actually has id="button":
<input id="button" type="button" value="Click on me" onClick="playAgain()" />
To re-enable the button set .disabled = false;

You're using document.getElementById("button") but there is no element named button in the HTML.
<input type="button" id="button" value="Click on me" onClick="playAgain()" />
Also, to disable a button, set its disabled attribute to true (false for otherwise).
document.getElementById('button').disabled = true;

with jquery you can say
$("[type=button]").click(function(){
$(this).attr("disabled","disabled");
... your other code ...
});

Related

disable click button on submit

I try to update this jquery script in pure js (with bootstrap 5). The goal is to not allow someone to click twice on the payment button. Sorry I am not very strong in js.
My goal is to have the same reaction that the jquery script.
I tried to follow the process on this page :
Disabling a button in vanilla JavaScript and in jQuery
Thank you
My current script
<form name="checkout_confirmation" action="http://............/Process" method="post" id="checkout_confirmation" role="form" onsubmit="return checkCheckBox(this)"><section class="checkout_confirmation" id="checkout_confirmation">
div class="text-end" id="process_button" class="processButton">
<button type="submit" data-button="payNow" class="btn btn-success">Confirmer la commande avec paiement</button> </div>
</div>
</form>
<script>
$('form[name="checkout_confirmation"]').submit(function() {
$('form[name="checkout_confirmation"] button[data-button="payNow"]').html('Confirm the payment').prop('disabled', true);
});
</script>
Now the script update
<script>
var button = document.getElementById('checkout_confirmation');
button.addEventListener('submit', function() {
alert('Confirm the payment');
});
button.disabled = false;
button.click(); // No output
button.prop("disabled", true);
</script>
setAttribute can be used in JavaScript to set the attribute of the button as disabled.
Element.setAttribute("disabled", true);
This can be used to disabled the button.
So when someone clicked on the submit button, you can disable the button till the data is processed.
Check the below demo code:
const btn = document.getElementById("submit-data");
btn.addEventListener("click", submitForm);
function submitForm(){
btn.setAttribute("disabled", true);
btn.innerText = "Submitting..";
let userName = document.getElementById("user-name").value;
console.log("Name: ", userName);
setTimeout(() => {
btn.removeAttribute("disabled");
btn.innerText = "Submit";
}, 3000);
}
<form type="POST">
<label for="user-name">Full Name</label>
<input type="text" id="user-name" placeholder="Your Full Name" />
<br /><br /><br />
<button id="submit-data">Submit</button>
</form>
You have two problems:
Submit events fire on form elements, not button elements.
getElementById gets an element by its id and neither your button nor your form has an id. (See this question).
Could you not use e.preventDefault() to stop the default behaviour of the button being pressed?
More can be read here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Disable Cancel button before POST

On clicking Submit button my JavaScript code execute $.post("Submit.aspx",... that sometimes takes a few seconds so user is able to click Back button that is undesirable.
So I try to disable or hide Back button but it does not work and it is still clickable. Any clue?
<input type="submit" value="Submit" class="next" onclick="submitData()" />
<input type="submit" id="btnBack" value="Back" onclick="goBack()" />
function submitData()
{
// I try to disable or hide Back button but it does not work
$('#btnBack').hide();
$('#btnBack').attr("disabled",true);
var btnBack= document.getElementById("btnBack").disabled = true;
// Long request
$.post("Submit.aspx",..
}
You should use $(el).prop() for disabling the input. Also when you are using jQuery, you don't need to add onclick in html, you can do it like Eg below:
$('input[value="Submit"]').on('click', function(e) {
$('#btnBack').prop("disabled",true);
//your post request
//$.post("Submit.aspx",..
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="Submit" class="next" />
<input type="submit" id="btnBack" value="Back" onclick="goBack()" />
For your code it will be:
function submitData() {
$('#btnBack').prop("disabled",true);
$.post("Submit.aspx",..
}
Your code seems to be right. Did you add Jquery?
Check the this:
function submitData(){
// I try to disable or hide Back button but it does not work
$('#btnBack').hide();
$('#btnBack').attr("disabled",true);
var btnBack= document.getElementById("btnBack").disabled = true;
}
function goBack(){
console.log("I'm back");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="Submit" class="next" onclick="submitData()" />
<input type="submit" id="btnBack" value="Back" onclick="goBack()" />
Try this ;)
canSubmit = true;
function submitData(){
if(!canSubmit){
return false;
}
canSubmit = false;
// disabling button
$('#btnBack').attr("disabled", true);
// Long request
$.post("Submit.aspx", ...).always(function(){ canSubmit = true; });
}
Simply use a variable and check for this value before submitting form and after ajax request response reset it value. BTW you can disable button if you want to do so.
$("#btnBack").prop('disabled', true);
Instead of
$('#btnBack').attr("disabled",true);

JavaScript generated code and screen readers

I'm asking you to help me out, I'm totally stuck with this problem.
I want to make possible my code to be navigated through keyboard and adoptable to screen reader devices. But I have several issues.
This is my code in JS:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
document.getElementById('div1').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn3" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
}
and HTML:
<div id="div1">
<input id="btn1" type='button' onclick='changeText()' value='Change Text'/>
</div>
when I navigate to btn1 in windows with keyboard only(with tab) and then press enter(or space) the button is changed, but it lose focus. As you may see, I tried to focus it with JS, but without a result. I also tried to use tabindex tag, but didn't help too. I want it to be focused when it is pressed, so it will be easier to navigate and to be accessible for screen readers.
Please help!
EDIT
Focus has been tested on the button with James Long solution and it works!
However, the btn.setAttribute('aria-hidden', true); should be removed.
Final EDIT
I just got it, lol! In order to MY example to work properly, I have should be focus to btn2 instead of btn1. This is so silly! So, it goes as follows:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn2').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn1" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').focus();
}
I feel proud of my self :)
I don't have a screen reader to hand so it's tricky to test this, but you might have better luck changing a button rather than replacing it and focussing on the button itself.
<div id="div1">
<button type="button" id="btn1">Change Text</button>
</div>
And then your JS:
document.addEventListener('DOMContentLoaded', function () {
function changeText(btn) {
btn.textContent = btn.textContent === 'Change Text'
? 'Change Text2'
: 'Change Text';
btn.setAttribute('aria-hidden', true);
btn.focus();
}
document.getElementById('btn1').addEventListener('click', function (e) {
changeText(e.target);
}, false);
}, false);
Put the focus on your button :
$("#btn1").focus();
In pure JS :
document.getElementById('btn1').focus();

I need to make all buttons disappear when one is clicked

Im writing a game of sorts that presents you with multiple options. Once you choose your option, all buttons, including your selection, should disappear and you move on to the next round. I have a script that allows this to be done, however for each round of buttons I would have to rewrite it to adhere to the new set of buttons. To save from having to repeat myself each time, I'm trying to get a universal script that will accomplish this
HTML
<input type="button" class="btn" id="getUp" name="answer" value="get up" onclick="this.style.display='none'; hideSleepIn(); " />
<input type="button" class="btn" id="sleepIn" name="answer" value="sleep in" onclick="this.style.display='none'; hideGetUp();" />
JavaScript
var hidden = false;
var click = onClick;
function hideSleepIn()
{
hidden = !hidden;
if(getUp === click)
{
document.getElementById('getUp').style.visibility = 'visible';
}
else
{
document.getElementById('sleepIn').style.visibility = 'hidden';
}
}
Try replacing
document.getElementById('getUp').style.visibility = 'visible';
with this
document.getElementById("getUp").style.display = 'none';
I worked the current script I was using to hide the divs, to also hide/ show the buttons on the page
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
<input type="button" class="unhidden" id="firstPath" value="get up" onclick="unhide('getUpText'); unhide('firstPath2'); unhide('firstPath');" />
text
<input type="button" class="unhidden" id="firstPath2" value="sleep in" onclick="unhide('sleepInText'); unhide('firstPath'); unhide('firstPath2');" />
text

Multiple JavaScript Buttons (Variables)

I'm just beginning JavaScript, and I was wondering how to make different buttons do different things. So far, I can make one button do one thing, but how do I make a second button do a different thing? Here's the coding:
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Your Name");
if (name!=null && name!="")
{
alert("Thanks for clicking " + name + "!");
window.top.location.replace("http://www.google.com");
}
}
</script>
</head>
<body>
<ul>
<li>
<input type="button" onclick="show_prompt()" value="Button One" />
</ul>
</body>
</html>
I will guess you meant like doing different things with different buttons but from the same function:
JavaScript:
function myFunction(str) {
if(str.length > 3){
alert("big");
}else{
alert("small");
}
}
HTML:
<input type="button" onclick="myFunction('test');" value="Button 1" />
<input type="button" onclick="myFunction('hi');" value="Button 2" />
In case my assumption is wrong, just create different functions and replace the button's onclick with their respective function
Define another function and bind the second button to it!
function alert_hi() {
alert("Hi!");
}
<input type="button" onclick="alert_hi()" value="Button Two" />
If that catches your interest I highly recommend Eloquent Javascript.
Making the second button do something is basically identical to making the first do something. It'd just be two functions and two buttons. I think this is what you're asking about.
<html>
<head>
<script type="text/javascript">
function doSomething()
{
// Do something when button one is clicked
}
function doSomethingElse()
{
// Do something else when button two is clicked
}
</script>
</head>
<body>
<input type="button" onclick="doSomething()" value="Button One" />
<input type="button" onclick="doSomethingElse()" value="Button Two" />
</body>
</html>
If you're serious about learning.. you can read up about Event Registration models.
in the case of your example.
js
var btn1 = document.getElementById('btn1'),
btn2 = document.getElementById('btn2');
btn1.addEventListener('click', show_me, false); // i am not IE friendly
btn2.addEventListener('click', show_me, false); // you can replace show_me with any function you would like.
function show_me() {
alert(this.value + ' was clicked'); // this references the element which the click event was invoked on.
}
html
<input type="button" id="btn1" value="Button One" />
<input type="button" id="btn2" value="Button Two" />

Categories