0

I have some elements in my document like:

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

I can access get the text using:

$("#myinputid").parent().text();

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

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

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.

Castro Roy
  • 7,623
  • 13
  • 63
  • 97
PurpleVermont
  • 1,179
  • 4
  • 18
  • 46

2 Answers2

2

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

Community
  • 1
  • 1
mh8020
  • 1,784
  • 1
  • 11
  • 14
  • Thanks, I chose option 2 (and put the span after the input) and used `$("myinputid").next("span")` to grab the span and change its text – PurpleVermont Sep 01 '16 at 21:39
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");
Daren Delima
  • 131
  • 8