Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disable element if select element have value

I want if test2 is selected from <option> then disable all element inputs by via id element1. I try with if but dosnt work for me

function myFunction() {
    if (document.getElementById("element0").value = "test2") {
        document.getElementById("element1").disabled = true;
    } else {
        document.getElementById("element1").disabled = !0;
    }
}
<select name="" id="element0">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
</select>

<div id="element1">
    <label for="your-name">Name: </label>
    <input type="text" name="your-name" id="" />
</div>

"Quick view" at https://jsfiddle.net/doLau1h2/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Generally, you should have better naming for your fields and elements. Element0 does not accurately describe what it is or does. I chose a simple name here, but please think of a better name yourself.

The function itself can be simplified. You can assign constants for the element references so that you can reuse some code. It is more readable like this and you don’t have to search twice for the same element (with .getElementById).

The disabled attribute can be the outcome of the expression, since it correlates.

function myFunction() {
  const dropdown = document.getElementById('dropdown');
  const name = document.getElementById('name');
  name.disabled = dropdown.value === 'test2';
}
<meta name="color-scheme" content="dark light" />

<body onload="myFunction()" oninput="myFunction()" style="zoom: 225%">

  <select name="dropdown" id="dropdown">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
  </select>

  <div>
    <label for="name">Name: </label>
    <input type="text" name="name" id="name" />
  </div>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading