I have looked everywhere and everyone says to use objectname.disabled = true
but in my project it doesn’t work. Even when asking ChatGTP it says "Huh… should work lol". Please help me out here!
My Code: (I do have a css file however it should not affect .disabled
not working so I will not add it here. I will after the fact if deemed necessary though.)
document.addEventListener('DOMContentLoaded', function() {
var atom_amount = 0;
var matter_btn = document.getElementById('matter_btn');
var matter_amount = 0;
var matter_cost = 10;
document.getElementById('atoms_btn').onclick = function() {
atom_amount++
document.getElementById('atoms_txt').innerHTML = "Atoms: " + atom_amount
if (atom_amount < matter_cost) {
matter_btn.disabled = true;
}
else {
matter_btn.disabled = false;
}
};
document.getElementById('matter_btn').onclick = function() {
atom_amount = atom_amount - matter_cost
document.getElementById('atoms_txt').innerHTML = "Atoms: " + atom_amount
matter_amount++
matter_cost = matter_cost + (2 * matter_amount)
document.getElementById('matter_txt').innerHTML = "Matter: " + matter_amount
};
});
<!DOCTYPE html>
<html>
<head>
<title>From Scratch</title>
<link rel="stylesheet" href="css/Style.css">
<script src="js/main.js"></script>
</head>
<body>
<game_name class="game_title">From Scratch</game_name>
<shape class="resource_area"></shape>
<resources_info class="text resources_text">Resources:</resources_info>
<shape class="divider"></shape>
<atoms id="atoms_txt" class="text atoms_amount">Atoms: 0</atoms>
<atoms_button id="atoms_btn" class="button atoms_button">Create Atoms</atoms_button>
<matter id="matter_txt" class="text matter_amount">Matter: 0</matter>
<matter_button id="matter_btn" class="button matter_button">Create Matter</matter_button>
</body>
</html>
I have created a test file and tried .disabled
and lo and behold it worked! However as soon as I went back to my main file it did again not work so I am extremely confused.
All I want is for my button to be disabled when certain conditions are met and to be reenabled when those conditions are not met.
2
Answers
you can inspire of this code
The problem is you’ve made up your own HTML tag,
matter_button
(and some others). Since it’s not a standard element tag, it just has a generic interface (HTMLElement
), which doesn’t provide thedisabled
reflected property thatbutton
(HTMLButtonElement
) andinput
(HTMLInputElement
) have. If you usedbutton
(probably withtype="button"
, redundant as that sounds) orinput
,disabled
would work.Here’s your code using
button
, with some other modernizations and suggestions inline (feel free to ignore them if you like):That’s just to get you started. I think there are probably still some logic errors in there (I wasn’t sure what the logic should be).