最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bootstrap4 toggle button - Stack Overflow

programmeradmin1浏览0评论

I'm using Bootstrap 4 to create a toggle button; however, on clicking the button the checkbox is not being updated, although the active class is being set.

Even calling $('.btn-group-toggle').button('toggle') sets the active state, but does not change the checked status of the checkbox.

<div class="btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-outline-secondary">
    <input type="checkbox" value="0" />
  </label>
</div>

Is there any way to set the checked status, other than writing a click() function myself?

I'm using Bootstrap 4 to create a toggle button; however, on clicking the button the checkbox is not being updated, although the active class is being set.

Even calling $('.btn-group-toggle').button('toggle') sets the active state, but does not change the checked status of the checkbox.

<div class="btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-outline-secondary">
    <input type="checkbox" value="0" />
  </label>
</div>

Is there any way to set the checked status, other than writing a click() function myself?

Share Improve this question edited Mar 8, 2018 at 18:12 Ramses asked Mar 6, 2018 at 21:10 RamsesRamses 9964 gold badges12 silver badges28 bronze badges 2
  • 1 How did you check if the checkbox wasn't updated? Because it should work: jsfiddle/aoc3fL1o – Ron van der Heijden Commented Mar 9, 2018 at 10:26
  • You're right! I was checking it with chrome dev tools, and I expected to see the checked value appear. I tested with a plain checkbox and the checked value did not appear. It is working, but somehow I was not adding a name, so I couldn't catch it on the server. – Ramses Commented Mar 9, 2018 at 14:45
Add a ment  | 

2 Answers 2

Reset to default 2

Your code works for me - I suspect you've not got the right JS included? I second-guessed myself migrating to 4 in terms of which of the many supplied JS files I'd need to include, it's not very documented. The bootstrap.bundle.js is the catch-all one that contains everything.

Also, there are a lot of little references to dependancies or quirks in Bootstrap that aren't particularly well highlighted. So be careful to ensure you add the right aria labels etc.

As Dan Brazier mentions, the HTML used is correct. I was missing the name attribute on the input, so that's why I was unable to catch it on the server. So this is the updated code:

<div class="btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-outline-secondary">
    <input name="my-input-value" type="checkbox" value="0" />
  </label>
</div>
发布评论

评论列表(0)

  1. 暂无评论