shu
shu

Reputation: 244

How to stop event propagation when checkbox input changes?

Description

I want to implement a table component with checkboxes. The problem I'm having is that when I click a checkbox, table row and table cell catch click event which I want to avoid. When I click a checkbox, I want only that checkbox react to the change event.

I tried event.stopPropagation method but it does not work. Somehow, before the checkbox catches the change event, table row and cell containing that checkbox react to the click event when I click the checkbox.

How can I achieve what I want? Please help me!!

Code

<template>
  <table>
    <tr @click="trClick">
      <td @click="tdClick">
        <input @change="checkboxChange" type="checkbox">
      </td>
    </tr>
  </table>
</template>

<script>
export default {
  name: "HelloWorld",
  methods: {
    trClick() {
      console.log("tr - click");
    },
    tdClick() {
      console.log("td - click");
    },
    checkboxChange(e) {
      e.stopPropagation();
      console.log("checkbox - change");
    }
  }
};
</script>

<style>
table {
  background: #cccccc;
  width: 100%;
  cursor: pointer;
}
input {
  cursor: pointer;
}
</style>

Demo Links

Vue.js Ver.

I want this Vue version work as I expect. https://codesandbox.io/s/pjxzvj9jvm

Vanilla JavaScript Ver.

I just tried the same thing in vanilla JavaScript just in order to investigate how event propagation in JavaScript works. https://codepen.io/anon/pen/xNxgeM?editors=1111

Animation GIFs

Vue.js Ver at codesandbox

enter image description here When I click the checkbox, what I want to see in the console is only "checkbox - change".

Vanilla JavaScript Ver at codepen

enter image description here

Upvotes: 4

Views: 4990

Answers (1)

TommyF
TommyF

Reputation: 7150

There is a built in solution in Vue to stop event propagation. Just use the @targetEvent.stop notation:

<input @click.stop @change="checkboxChange" type="checkbox">

Upvotes: 7

Related Questions