how to disable a label tag in javascript

29,738

Solution 1

Before looking at your example, I would have said:

A label can't be disabled. One of the effects it has is to extend the click target of a form control, so you probably want to disable the form control instead.

However, for some reason, all your labels are associated with the same control (the one with id="u"), which suggests that you aren't using <label> correctly. It is possible to have multiple labels for a single control, but it doesn't look like you are doing that.

You should probably take a step back and describe the problem that you think disabling a label will solve.

Solution 2

You can see in the source a whole solution using Javascript and CSS. But if you want labels "look" like disabled you can use CSS this way:

In HTML

<label  class="disabled" for="u">username1 </label> 

In CSS

label.disabled { color: #aaa; }

Solution 3

You, cant disable the Labels. Instead u can set the Text property of the label to "" when one label is clicked for the other ones.

Solution 4

The correct way to do would be to not only make it look disabled but also to disable any action on click of it. I would use the below code for this purpose:

In HTML

<label  class="disableLabel" for="u">username1 </label> 

In CSS

.disableLabel {
    pointer-events: none;
    opacity: 0.5;
}
Share:
29,738
mere
Author by

mere

Updated on July 16, 2022

Comments

  • mere
    mere almost 2 years

    i need to create five labels using <label> tag in html. then when any one of the label is clicked all the other four labels must be disabled. i have searched through the google but could not find how to disable label tag. is there any way to do that .any suggestion......

    <label for="u">username1</label>
    <label for="u">username2</label>
    <label for="u">username3</label>
    <label for="u">username4</label>
    <label for="u">username5</label>
    
    • sdleihssirhc
      sdleihssirhc almost 13 years
      Labels can't really be disabled. Do you mean "disappeared"?
    • shinkou
      shinkou almost 13 years
      I don't see what you mean by disabling a label.
    • Jordan
      Jordan almost 13 years
      Please describe the problem you are trying to solve. There's probably a better solution.
    • user229044
      user229044 over 3 years
      You should absolutely not do this. This is now how HTML is supposed to work, it's inaccessible to assistive devices and semantically completely wrong. Use <option>, it's specifically built for this purpose.
  • MidnightJava
    MidnightJava over 10 years
    This worked for me, thanks. I have a checkbox and a label, and when I disable the checkbox I want the label to have the same appearance of being disabled. Otherwise it's easy to miss that the checkbox is disabled. I think this is the same effect the OP was looking for.