Home > Net >  Disabling a checkbox if a condition is met
Disabling a checkbox if a condition is met

Time:09-21

I'm pretty new to Javascript and I have an exercise containing a form and some validation checks, I have a few inputs such as name, price, and a checkbox and I'm trying to disable the checkbox based on the price input (disable it if it's above 200 and re-enable it if it's less than 200), and at the moment it's not working, I'll really appreciate suggestions.

That's the Javascript code I've written:

document.addEventListener("DOMContentLoaded", function () {
  const price = document.querySelector("[name='purchasePrice']");
  price.addEventListener("change", checkPrice);
  function checkPrice() {
    if (price > 200) {
      document.querySelector("[name='chkBx']").disabled = true;
    } else {
      document.querySelector("[name='chkBx']").disabled = false;
    }
  }
});

and this is the HTML code:

<div >
    <label>
      Purchase Price
      <input
        
        type="number"
        name="purchasePrice"
        min="1"
        required
      />
    </label>
  </div>
  <div >
    <label>
      Add Charge
      <input type="checkbox" name="chkBx" />
    </label>
  </div>

CodePudding user response:

Just put a parameter name e in checkprice function.And then you will get access to the target value in change event then your function will work fine.

func checkprice (e)

if(e.target.value > 250)

disable true

else

disable false

end of function

Hope it helps.

  • Related