通过它的类(不是id)禁用文本区域

时间:2013-07-16 13:45:59

标签: javascript html forms

我有2个文本区域是自动生成的,我需要使用JavaScript来禁用页面加载时。问题是因为它们是自动生成的,我不能给它们一个ID,因为它们都有ID - 一个大的没有

尝试使用Javascript:

document.getElementByClassName('option_window-size').disabled=true;

我知道这是有效的,因为如果我将 getElementbyClassName 更改为ID,那么如果我同时给文本区域ID,它也会起作用。但正如我所说,它需要在课堂上工作。此外,它无法使用Name属性,因为它是按产品和每页自动生成的......

我试过这个,但它不起作用,我无法弄清楚为什么不行,因为它应该是我唯一改变的是从ID到CLASS

文字区域

<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>

附加说明:我已经尝试使用PHP计算并为它们分配不同的ID但它变得复杂得多。此外,只有这两个需要禁用,因此我不能只禁用页面上的所有文本区域。

8 个答案:

答案 0 :(得分:8)

  

我知道这是有效的,因为如果我将getElementByClassName更改为ID,那么如果我同时给文本区域ID,它也会起作用。但正如我所说,它需要在课堂上工作。

getElementsByClassName返回 NodeList 而不是 Node 本身。您必须循环遍历列表,或者如果您只期望1项,请选择索引0

var nodes = document.getElementsByClassName("option_window-size"),
    i = 0, e;

while (e = nodes[i++]) e.disabled = true;

答案 1 :(得分:2)

jQuery使这很简单:

$(".selector").prop("disabled", true);

<强>虽然!请注意,此注释显示在$.prop()$.attr()

的手册页上
  

注意:尝试更改通过HTML或已在HTML文档中创建的输入元素的type属性(或属性)将导致Internet Explorer 6,7或8抛出错误。

这不直接适用于您的问题,但您要更改输入元素上的prop / attr,因此请注意。

但是仍然可以使用普通的旧JS:

var els = document.getElementsByClassName("selector"); // note: Elements, not Element

for(var e = 0; e < els.length; e++)
{
    els[e].disabled = true;
}

getElementsByClassName返回一个NodeList,你只需迭代其中的每个元素。

答案 2 :(得分:1)

您可以使用班级选择器

$('.option_window').attr('disabled', true);

OR

$('.option_window')[0].disabled = true;

答案 3 :(得分:1)

使用Jquery,您可以:

//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);

答案 4 :(得分:0)

使用jQuery禁用textarea:

$('.option_window-size').attr('disabled', true);

答案 5 :(得分:0)

缺少元素中的s和第一个元素的元素类似的索引[0]。

  document.getElementsByClassName('option_window-size')[0].disabled=true;

  document.getElementsByName('willbeautogenerated')[0].disabled=true;

答案 6 :(得分:0)

在jquery ...

中使用 .prop()方法禁用textarea
      $('.option_window-size').prop('disabled', true);

答案 7 :(得分:0)

您可以使用CSS:

.option_window-size{display:none;}