admin管理员组

文章数量:1317898

I want to call a function updateText() when I click on the checkbox text_mode. I've tried using onClick="updateText()" but it didn't work. I have read some ments on similar questions, but all answers are using jQuery, can I do it without using any libraries, because all the js code for this project is done without any libraries?

This is the checkbox:

<label class="checkbox-inline">
   <input type="checkbox" checked data-toggle="toggle" data-size="mini" data-onstyle="default" id="text_mode" onclick="updateText()">
</label>

I want to call a function updateText() when I click on the checkbox text_mode. I've tried using onClick="updateText()" but it didn't work. I have read some ments on similar questions, but all answers are using jQuery, can I do it without using any libraries, because all the js code for this project is done without any libraries?

This is the checkbox:

<label class="checkbox-inline">
   <input type="checkbox" checked data-toggle="toggle" data-size="mini" data-onstyle="default" id="text_mode" onclick="updateText()">
</label>
Share Improve this question edited Apr 23, 2019 at 8:17 Misho Tek asked Sep 15, 2017 at 19:18 Misho TekMisho Tek 6542 gold badges11 silver badges23 bronze badges 4
  • 2 You could use an onchange="updateText()" event handler – brenjt Commented Sep 15, 2017 at 19:29
  • 1 If you are using Bootstrap, I'm 99% sure you have jQuery already loaded and ready to use. – zer00ne Commented Sep 15, 2017 at 19:30
  • Possible duplicate of Fire an event on input.checked=true/false _without_ jQuery – Brr Switch Commented Sep 15, 2017 at 19:33
  • Yes, that's true, but in the whole code for updateText() function (and whole js file) I was using pure js, so it wouldn't be good to use jquery just for one function. – Misho Tek Commented Sep 15, 2017 at 19:33
Add a ment  | 

3 Answers 3

Reset to default 4

Use the onchange event

<label class="checkbox-inline">
    <input type="checkbox" checked ... onchange="updateText()"> Braille
</label>

That will execute it regardless of clicking the checkbox. So if you trigger the label it will also be executed.

Try this:

document.getElementById('text_mode').addEventListener('click', function(){
	console.log('updateText executed')
});
<label class="checkbox-inline">
   <input type="checkbox" checked data-toggle="toggle" data-size="mini" data-onstyle="default" id="text_mode"> Braille
</label>

In version 3.5, the same problems. Added an event call to the library:

$(document).on('touch.bs.toggle click.bs.toggle', 'div[data-toggle^=toggle]', function (e) {
    var $checkbox = $(this).find('input[type=checkbox]')
    $checkbox.bootstrapToggle('toggle')
    $checkbox.trigger("click")    // <!-- Added line
    e.preventDefault()
})

My problem was solved.

本文标签: javascriptCall function on click on Bootstrap toggle (checkbox)Stack Overflow