Search code examples
vue.jsonclickonchange

VueJS Using @click on <option> elements and @change on <select> element


I have a simple function that manipulates a data between true and false. I use it to make my div hidden and visible like a toggle. I also have a with three element. I found out that I cannot use @click for <option> elements, I need to use @change for my <select>.

But in this way, whenever an is selected, the function is being triggered and my data toggles between true and false. Here is my <select> element;

       <select @change="isDisabled">
          <option>Please select a security type</option>
          <option>No Security</option>
          <option>Personal</option>
          <option>Enterprise</option>
       </select>

IsDisabled function takes a variable and change its values between true and false so my div becomes hidden and visible as follows;

<div v-if="noSecurity">something</div>

But here is the thing, I only want to trigger the function when the user select the "No Security" option. Now it's being triggered whenever I select an option, so it turned out to be some kind of a toggle. But I want to hide the div when I select the "No Security" option and show the div if something different is selected. What should I do?


Solution

  • There's no need for the additional noSecurity variable. Create your select with v-model to track the selected value. Give each option a value attribute.

    <select v-model="selected">
      <option value="">Please select a security type</option>
      <option value="none">No Security</option>
      <option value="personal">Personal</option>
      <option value="enterprise">Enterprise</option>
    </select>
    

    Check that value:

    <div v-if="selected === 'none'">something</div>
    

    You can still use the noSecurity check if you prefer by creating a computed:

    computed: {
      noSecurity() {
        return this.selected === 'none';
      }
    }
    

    Here's a demo showing both:

    new Vue({
      el: "#app",
      data() {
        return {
            selected: ''
        }
      },
      computed: {
        noSecurity() {
          return this.selected === 'none';
        }
      },
      methods: {},
      created() {}
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <select v-model="selected">
        <option value="">Please select a security type</option>
        <option value="none">No Security</option>
        <option value="personal">Personal</option>
        <option value="enterprise">Enterprise</option>
      </select>
    
      <div v-if="selected === 'none'">something</div>
      <div v-if="noSecurity">something</div>
    </div>