PurpleVermont PurpleVermont - 4 months ago 9
jQuery Question

Modifying the text of a label that also contains an input (checkbox)

I have some elements in my document like:

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

I can access get the text using:


This returns
as I had hoped it would. That is:


Changes my initial element to

<div class="checkbox-inline"><label>newtext</label></div>

How can I change the text part without removing the input? Or do I have to reconstruct it?

If there's a better way to structure my checkboxes to begin with, that would be an acceptable alternative.


(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">

(2) Another option would be to restructure as:

<div class="checkbox-inline">
    <input id="myinputid" value="False" type="checkbox">

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)