Disable text box using class name in Javascript

无人久伴 提交于 2019-12-10 15:35:27

问题


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.


回答1:


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/




回答2:


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.




回答3:


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;
});


来源:https://stackoverflow.com/questions/29532597/disable-text-box-using-class-name-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!