Home > other >  Disabling a dropdown if a Textfield contains a certain value
Disabling a dropdown if a Textfield contains a certain value

Time:10-11

I have an issue with HTML and Javascript where I'm trying to create a condition that follows the following rules:

If the first text-box contains a certain word, disable the following drop-down. If it doesn't contain that certain word, keep it enabled.

So far, I've got this code

var noSample = "HW8020";
const interval = setInterval(function() {
      // method to be executed;
      function codeCheck() {
        var x = document.getElementById("form-RequestAQuoteUK-9bbb_Products_Interest_Value").value;
      }
      function validateSample() {
      if ( x == noSample) {
        document.getElementById(
          "form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue"
        ).disabled = true;
      } else {
        document.getElementById(
          "form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue"
        ).disabled = false;
      }
    }
}, 5000);

The noSample variable being the code that, when input into the text-field, will disable the dropdown. The Ids weren't my choice of naming, but I'm new to Javascript and am trying to fix an issue with the company I work for!

Any ideas?

CodePudding user response:

You should rather use event input instead of setInterval and use indexOf to check if input.value contains certain value.

var noSample = "HW8020";
let input = document.getElementById(
    "form-RequestAQuoteUK-9bbb_Products_Interest_Value",
);

input.addEventListener("input", () => {
    validateSample(input.value)
});

function validateSample(inputValue) {
    let selectEl = document.getElementById(
        "form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue",
    );
    if (inputValue.indexOf(noSample) > -1) {
        selectEl.disabled = true;
    } else {
        selectEl.disabled = false;
    }
}

CodePudding user response:

As suggested in the comments, you can add an event listener to your Products_Interest_Value input and then enable or disable the dropdown based on whether or not this matches your noSample value.

const noSample = "HW8020";

document.querySelector("#form-RequestAQuoteUK-9bbb_Products_Interest_Value").addEventListener("input", e => {
  document.querySelector("#form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue").disabled = (e.target.value == noSample);
});

  • Related