2

I want to get a select option name attribute in vuejs. I tried it to value attributes. It worked well. I have mentioned the tried code below.

Tried code:

<select id="countryselect" name="country" @change="onChange()">
  <option value="1" name="0">Afghanistan</option>
  <option value="2" name="0">Albania</option>
  <option value="3" name="0">Algeria</option>
  <option value="4" name="1">Malaysia</option>
  <option value="5" name="0">Maldives</option>
</select>

var app = new Vue({
  el: '#app',
  methods: {
    onChange: function() {
      //this workes well
      var b = event.target.value;
      // this not workes
      var c = event.target.name;
    }
  },
});

I want to know how can I do this. Thank you.

1 Answer 1

2

event.target.name actually returns the name attribute of the select element instead of the selected option. To get the name attribute of the selected option you can use getAttribute() method instead like:

var app = new Vue({
  el: '#app',
  methods: {
    onChange: function() {
      var options = event.target.options
      if (options.selectedIndex > -1) {
        var name = options[options.selectedIndex].getAttribute('name');
        console.log(name)
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <select id="countryselect" name="country" @change="onChange()">
    <option value="0">---Select---</option>
    <option value="1" name="0">Afghanistan</option>
    <option value="2" name="0">Albania</option>
    <option value="3" name="0">Algeria</option>
    <option value="4" name="1">Malaysia</option>
    <option value="5" name="0">Maldives</option>
  </select>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.