6

I have multiple buttons name="angka" and id="angka":

<input type="button" name="angka" id="angka" value="1" style="width:15px" onclick="insert(1)">
<input type="button" name="angka" id="angka" value="2" style="width:15px" onclick="insert(2)">
<input type="button" name="angka" id="angka" value="3" style="width:15px" onclick="insert(3)">

onLoadPage event I try to disabled them with the below code.

document.getElementById("operator").disabled = true; 
document.getElementsByName("operator").disabled = true; 

But the result is that only the first button is disabled, the other buttons are still enabled.

How to disable the buttons with JavaScript without making unique names or ids?

solve with

`var elements = document.getElementsByClassName("classname");

for (var i = 0; i < elements.length; i++) {
  elements[i].disabled =true;
}`
7
  • 5
    First problem: each of your buttons should have a different id. Commented Jun 30, 2013 at 13:12
  • 1
    Your HTML is invalid, Use class instead of ID. Commented Jun 30, 2013 at 13:13
  • 1
    Also, why would you disable them onloadpage? Just disable them in the html. Commented Jun 30, 2013 at 13:14
  • could i disabled that button with class attribute? hows? Commented Jun 30, 2013 at 13:14
  • @arbitter i have requirement to change state the button based on user action. so i need disabled that things whenever user want it(not only at begining). Commented Jun 30, 2013 at 13:17

1 Answer 1

11

As @Red said: Use class instead of ID

<input type="button" name="angka" class="angka" value="1" style="width:15px" onclick="insert(1)">

After that, you should be able to do something like this:

var elems = document.getElementsByClassName("angka");
for(var i = 0; i < elems.length; i++) {
    elems[i].disabled = true;
}

I'm not sure getElementsByClassName() is cross-browser, so take care. However, jQuery is good at this, so you could use that and make your life more simple.

EDIT

jQuery (untested) example for that:

$('input.angka').attr('disabled','disabled');
Sign up to request clarification or add additional context in comments.

2 Comments

getElementsByClassName returns an array of elements. You can't set the attribute of the entire array at once, you have to loop through it and handle each element individually.
some crumbs from me too: for with total where var total = elems.length; works faster then count it each loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.