0
<form>
    <input type="text" id="name" onkeydown="myHandler()"/>
    <select id="select">
        <option value = "a">a</option>
        <option value = "b">b</option>
    </select>
</form>

<script>
    function myHandler() {
        if(document.getElementById("name")){
            document.getElementById("select").disabled = true;
            return;
        }
        document.getElementById("select").disabled = false;
    }
</script>

Well, this is all I have done. This disables the select whenever I input something in input but the select will stay disabled even if erase all the inputs in the input box. What can I do to make the select selectable if the input field is empty?

1
  • what will be the initial state of select Commented Sep 23, 2018 at 11:54

3 Answers 3

1

I would use onkeyup event to check the input value of the text box because the onkeydown event fire up after key down so while there is a single character in the text box it needs to clear one more time to check for the empty value condition.

The demo with your code is:

function myHandler() {
 console.log(document.getElementById("name").value.trim());
 if (document.getElementById("name").value.length == 0) {
  document.getElementById("select").disabled = false;
  return;
 } else {
  document.getElementById("select").disabled = true;
 }
}
<form>
    <input type="text" id="name" onkeyup="myHandler()"/>
    <select id="select">
        <option value = "a">a</option>
        <option value = "b">b</option>
    </select>
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

You can check the content to disabled it:

  function myHandler() {
    var input = document.getElementById("name");
    var select = document.getElementById("select");
    if(input && input.value){
      select.disabled = true;
    } else {
      select.disabled = false;
    }
  }

See that code in Codepen: https://codepen.io/rodrigo73/pen/PdgewR?editors=1000

2 Comments

please use onchange="myHandler()". onkeydown there isn't yet any input.value and won't disable the select.
onchange is triggered only on focus lost. Maybe the oninput event can improve this.
0

There is no reason document.getElementById("name") will be null when you empty the input. You have to check the value of the input as well.

if(document.getElementById("name") && document.getElementById("name").value){
    document.getElementById("select").disabled = true;
    return;
}

document.getElementById("select").disabled = false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.