Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Get the name of the clicked Button If the v-on directive is in the Form Tag

Tags:

vue.js

Is it possible to get the submit button name that is being clicked if the v-on:submit is placed on the form tag and not in the button?

Form

<form method="post" @submit.prevent="getButtonName($event)">
    <input type="submit" name="button1" value="Button1">
    <input type="submit" name="button2" value="Button2">
</form>

Script

methods: {
    getButtonName(event) {

    }
}
like image 453
Kay Singian Avatar asked Dec 02 '25 09:12

Kay Singian


2 Answers

v-on:submit won't work. but v-on:click will. See @click="handleClick($event)"

<template>
    <div class="hello">
    <form method="post" @click="handleClick($event)" @submit.prevent="getButtonName($event)">
      <input type="submit" name="button1" value="Button1">
      <input type="submit" name="button2" value="Button2">
    </form>
    </div>
</template>

<script>
    export default {
  name: 'hello',
  data () {
    return {

    }
  },
    methods: {
    getButtonName(event) {
            // console.log(event);
    },
    handleClick(e) {
      console.log(e.target.name);

    }
  }
}

</script>

e.g. https://codesandbox.io/s/6jwvy6l96k

like image 173
Jacob Goh Avatar answered Dec 04 '25 23:12

Jacob Goh


new Vue({
  el: "#app",
  data() {
    return {
    	clickedButton: null,
    }
  },
  methods: {
    getButtonName(event) {
    	this.clickedButton = event.target.name
    }
  }
})
<html>
  <head></head>
  <body>
    <div id="app">
      <form method="post" @click.prevent="getButtonName">
        <input type="submit" name="button1" value="Button1">
        <input type="submit" name="button2" value="Button2">
      </form>
      <div v-text="clickedButton" v-if="clickedButton"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </body>
</html>
like image 20
tiagojpdias Avatar answered Dec 05 '25 00:12

tiagojpdias