Geetika
Geetika

Reputation: 820

How to enable text box on drop down value change in javascript

I have a textbox disabled by default, and i want to enable it on the drop down onchange() event.

I tried this but not working:

<!DOCTYPE html>
<html>

<body>
    Name:
    <input type="text" id="myText" disabled="true">
    <p>Click the button to disable the text field.</p>
    <select onchange="myfunction()">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
    <script>
    function myFunction() {
        document.getElementById("myText").disabled = false;
    }
    </script>
</body>

</html>

What is the right one?

Upvotes: 2

Views: 4186

Answers (3)

Tushar
Tushar

Reputation: 87203

Javascript is case-sensitive language.

The problem in your code is that the function name is mis-spelled

onchange="myfunction()"

And in javascript(Notice capital F)

function myFunction() {

Change the function name, and then it'll work.

Demo

function myFunction() {
  document.getElementById("myText").disabled = false;
}
Name:
<input type="text" id="myText" disabled="true">
<p>Click the button to disable the text field.</p>
<select onchange="myFunction()">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

Also, use addEventListener to bind events.

Demo

Upvotes: 1

Rohit Palande
Rohit Palande

Reputation: 54

java script is case sensitive language just change function myFunction() to function myfunction()

    function myfunction() {
        document.getElementById("myText").disabled = false;
    }
<html>

<body>
    Name:
    <input type="text" id="myText" disabled="true">
    <p>Click the button to disable the text field.</p>
    <select onchange="myfunction()">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
   
</body>


</html>

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Symbols in JavaScript are cases sensitive. You've named your function myFunction, but try to call it with myfunction.

Also, do not use inline event handlers! Use .addEventListener() in your JavaScript part like so:

function enableText() {
    document.getElementById("myText").disabled = false;
}
//                     You'll need to add a class name to your select
document.querySelector('.mySelect').addEventListener('change', enableText);

function enableText() {
        document.getElementById("myText").disabled = false;
    }
    //                     You'll need to add a class name to your select
    document.querySelector('.mySelect').addEventListener('change', enableText);
Name:
    <input type="text" id="myText" disabled="true">
    <p>Click the button to disable the text field.</p>
    <select class="mySelect">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>

Upvotes: 1

Related Questions