Michael
Michael

Reputation: 11

Bootstrap 3 group-button behavior

I have regular group-button behavior with label and radio buttons:

<div class="btn-group" data-toggle="buttons">
  <label class="btn" id="lblAct1">
    <input type="radio" value="Val1">
    Act1
  </label>
  <label class="btn" id="lblAct2">
    <input type="radio" value="Val2">
    Act2
  </label>
  <label class="btn" id="lblAct3">
    <input type="radio" value="Val3">
    Act3
  </label>
</div>

When I am changing title of label with $("#lblAct1").html(getTranslation("ACT1")) elements of button-group stops behavior as required(pressed item became active, others non-active)

Please help.

Upvotes: 0

Views: 44

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337700

The problem is because html() overwrites all content in the target element, not just the text nodes. In addition as you're dealing with text content and not HTML, you can use the text() method to help prevent XSS attacks.

Also note that, assuming these radio inputs are related, they need to have the same name attribute in order for them to be grouped correctly.

The simple fix for your situation is to place the text node within another element, for example a span, and then set the text() of that element instead:

let getTranslation = input => input + ' translation here...';

$("#lblAct1 span").text(getTranslation("ACT1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-group" data-toggle="buttons">
  <label class="btn" id="lblAct1">
    <input type="radio" value="Val1" name="foo" />
    <span>Act1</span>
  </label>
  <label class="btn" id="lblAct2">
    <input type="radio" value="Val2" name="foo" />
    <span>Act2</span>
  </label>
  <label class="btn" id="lblAct3">
    <input type="radio" value="Val3" name="foo" />
    <span>Act3</span>
  </label>
</div>

Also note that you can make your translation code completely dynamic by providing the text of the element to the getTranslation() function straight from the DOM, instead of hard-coding it, and attaching N number of method calls:

let getTranslation = input => input + ' translation here...';

$(".translatable span").text((i, t) => getTranslation(t))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-group" data-toggle="buttons">
  <label class="btn translatable">
    <input type="radio" value="Val1" name="foo" />
    <span>Act1</span>
  </label>
  <label class="btn translatable">
    <input type="radio" value="Val2" name="foo" />
    <span>Act2</span>
  </label>
  <label class="btn translatable">
    <input type="radio" value="Val3" name="foo" />
    <span>Act3</span>
  </label>
</div>

Upvotes: 0

Related Questions