简体   繁体   中英

disabling buttons using javascript

I have four buttons with button2 as id.

document.getElementById('button2').disabled=true;

With the above code, Only one button is disabled. I want all buttons to be disabled.
Any ideas.
Thank you.

I have four buttons with button2 as id.

Don't do that, it's invalid . id values must be unique in the document.

Instead, perhaps give them the same class :

<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">

Then on modern browsers you can do this:

var list = document.querySelectorAll(".button2");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].disabled = true;
}

That works on current versions of, well, nearly everything. It doesn't work on IE7 and earlier. If you need to support those, I recommend using a decent DOM manipulation library (like jQuery , YUI , Closure , or any of several others ), which will have the ability to look up elements by class.


Alternately, you can give them the same name and use the older getElementsByName , which is on even IE6 and IE7:

<input type="button" name="button2">
<input type="button" name="button2">
<input type="button" name="button2">
<input type="button" name="button2">

Then much the same loop:

var list = document.getElementsByName("button2");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].disabled = true;
}

But there are a couple of caveats to using name for this:

  1. If this is in a form , while it would be fine in this case to do this because these are buttons , you may not want to use name for this in the general case. If you use the same name for multiple text fields or select boxes, for instance, you have to be sure you handle that right on the server-side when you receive the repeated field names.

  2. Similarly, while fine for this use, name is only a valid attribute on form fields, not other kinds of elements. So again while okay for buttons, you don't want to generalize it.

  3. Be careful not to use "button2" as an id on that same page, because IE8 and earlier have a bug in them that will make it act like that element has the name "button2" even though it doesn't. It's the same bug I talk about here in relation to getElementById .

So in general, class is probably the better way to go.

There should only be 1 occurence of an id value on a single page. Use different id values for each button (eg, use id="button1" for one button, and id="button2" for the other button.

Then you can disable each of the buttons, one at a time:

document.getElementById('button1').disabled=true;
document.getElementById('button2').disabled=true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM