Home > database >  HTML/vue.js - disable select list when checked
HTML/vue.js - disable select list when checked

Time:11-24

I have a form with the field "age". There are two possible scenarios: either I check the "unknow" box and then you can't enter/select an age (in other words, this option should be disabled) or the box is not checked, and then you can enter the age. However, I can't do the first scenario at all. Here is my code:

<div class="row mb-3">
<label for="age" class="col-sm-2 col-form-label"> Age </label>
<div class="col-sm-10">
<input type="number"class="col-sm-3 col-form-control" min="0" max="120" step="1" id="age">
</div>
<div class="row mb-3">
<label class="col-sm-1 col-form-check-label"> Unknow </label>
<input class="form-check-input" type="checkbox" id="check1" name="option1" value="something">
</div>
</div>

Is it possible to do this with vue.js? Thank you in advance!!

CodePudding user response:

Here is your first scenario.

const checkBox = document.getElementById('check1')
const input = document.getElementById('age')

checkBox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    input.disabled = true
  } else {
    input.disabled = false
  }
})
<div class="row mb-3">
  <label for="age" class="col-sm-2 col-form-label"> Age </label>
  <div class="col-sm-10">
    <input type="number" class="col-sm-3 col-form-control" min="0" max="120" step="1" id="age">
  </div>
  <div class="row mb-3">
    <label class="col-sm-1 col-form-check-label"> Unknow </label>
    <input class="form-check-input" type="checkbox" id="check1" name="option1" value="something">
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do with both. The thing is, you should understand how it works in plain JavaScript first before jumping to any kind of JavaScript framework, hope that makes sense

const app = new Vue({
  el: "#app",
  data() {
    return {
      checkedStatus: false,
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="row mb-3" id="app">
  <label for="age" class="col-sm-2 col-form-label"> Age </label>
  <div class="col-sm-10">
    <input type="number" class="col-sm-3 col-form-control" min="0" max="120" step="1" id="age" :disabled="checkedStatus">
  </div>
  <div class="row mb-3">
    <label class="col-sm-1 col-form-check-label"> Unknow </label>
    <input class="form-check-input" type="checkbox" id="check1" name="option1" value="something" @change="checkedStatus=!checkedStatus">
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related