Skip to content Skip to sidebar Skip to footer

Modifying The Text Of A Label That Also Contains An Input (checkbox)

I have some elements in my document like:

Solution 1:

(1) Using the "for" attribute would be one option: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#Using_the_for_attribute

Since the <input> is no longer child of the <label>, the input won't be affected by your changes with text().

<div class="checkbox-inline">
  <label for="myinputid">mytext</label>
  <input id="myinputid" value="False" type="checkbox">
</div>

(2) Another option would be to restructure as:

<div class="checkbox-inline">
  <label>
    <span>mytext</span>
    <input id="myinputid" value="False" type="checkbox">
  </label>
</div>

Then you can change the span's text without modifying the input. A span within a label is allowed according to here: Is <div> inside <label> block correct?

(3) Here might be a possible solution for your original HTML structure: jQuery - setting an element's text only without removing other element (anchor)


Solution 2:

You can put your text inside an element for example a span and then use the .siblings() function instead of the .parent() function.

<div class="checkbox-inline">
  <label>
    <input id="myinputid" value="False" type="checkbox">
    <span>mytext</span>
  </label>
</div>

$("#myinputid").siblings().text("newtext");

Post a Comment for "Modifying The Text Of A Label That Also Contains An Input (checkbox)"