Disable text box using class name in Javascript
Asked Answered
T

4

9

I have HTML

Name 1:<input type="text" class="one" id="mytext">
<button onclick="disfunction()"></button>

Javascript

function disfunction(){
document.getElementsByClassName("one").disabled = true;
}

But the text box is still enabled. How can I disable text box using the classname in JAVASCRIPT.

Using id I can do this. Also using jquery.

But I need a solution using Javascript and classname.

Trillby answered 9/4, 2015 at 7:39 Comment(1)
why of all use class than id?Workbench
P
12

getElementsByClassName return a list of elements, you need to loop througth it to disable each element :

var cells = table.getElementsByClassName("one"); 
for (var i = 0; i < cells.length; i++) { 
    cells[i].disabled = true;
}

JSFIDDLE : http://jsfiddle.net/7L14zaha/1/

Pulchritude answered 9/4, 2015 at 7:41 Comment(0)
W
5

You may try this, and I bet is what you are looking at.

function disfunction(){
document.getElementsByClassName("one")[0].disabled = true;
}

JSFiddle :- Disable on click.

Workbench answered 9/4, 2015 at 7:49 Comment(0)
B
1

Mozilla docs states that:

elements is a live HTMLCollection of found elements.

So you have to iterate through the result of getElementsByClassName.

var testElements = document.getElementsByClassName('class-name-here');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
    testElement.disabled = true;
});
Bein answered 9/4, 2015 at 7:52 Comment(0)
K
0

2023 Update

I'm sure this is answered elsewhere, but the following is a good answer with ES6:

document.querySelectorAll(".class-name").forEach(element => element.disabled = true);
Kif answered 26/9, 2023 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.