-1

I'm trying to empty the HTML of this input and label via jQuery.

<input id="inputclass" type="checkbox">

<label for="labelclass">Text</label>

For the input it seems to be as simple as doing $(".inputclass").html(""); with jQuery, but what about for targeting the label?

Phiter
  • 14,570
  • 14
  • 50
  • 84
m0a
  • 1,005
  • 2
  • 15
  • 29
  • Is the code right? The label is not for `inputclass` but for `labelclass` which is not in the code. However, you can target the label by giving it an ID like `inputclass-label`, or targetting it with `$("[for=inputclass]")` – Phiter Jul 19 '20 at 20:37
  • 1
    The `for` attribute value has to be an "id" of some `` element, not a class. – Pointy Jul 19 '20 at 20:39

2 Answers2

1

jQuery selectors are basically CSS selectors, so:

$('label[for="labelclass"]').html('')

Also, <input> fields don't have an "html" property, so $('input').html('') has no effect.

kmoser
  • 8,780
  • 3
  • 24
  • 40
1

First, an input can't contain HTML, it has a value, so the correct way to clear its value out would be:

$("#inputclass").val("");

Unless you want to deselect the checkbox, in which case it would be:

$("#inputclass").prop("checked", false);

A label, on the other hand, may contain nested HTML, so for it you can target the element type and then its for attribute value:

$("label[for='labelclass']").html("");
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • 1
    Alternative/preferred way to set `checked` property is to use `.prop()`: https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery – kmoser Jul 19 '20 at 20:48