Home » vue » How to get cell value when that cell is clicked?

How to get cell value when that cell is clicked?

Posted by: admin November 26, 2021 Leave a comment

Questions:

When user clicks a table cell Vue should be aware of its value. In this case I am trying to set an event and pass the value.

Is there any way I could write this better, maybe from Vue itself – for example when the cell is clicked first get its content? I have many cells in table, and this doesn’t work, it works only if I remove PHP part and try to write it manually – @click="calculate_price(10)

<?php foreach ($tr as $td) : ?>
    <td @click="calculate_price(<?php echo $td['price']; ?>)">
        <?php echo $td['price']; ?>
    </td>
<?php endforeach; ?>


var app = new Vue({
    el: '#app',
    data: {
        price: 0
    },
    methods: {
        calculate_price: function (price) {
            console.log(price);
        }
    }
})

Vue version is 2.4.2

Answers:

You can bind the click event to the <table> and get the deepest element from the event to see which <td> was clicked and what value is in there.

See this fiddle: https://jsfiddle.net/at0sdhsh/