简体   繁体   中英

Disabled input tag based on dropdown value is not working

I'm going to create a dropdown list that contains four values (One, Two, Three, Four). When user chooses (One, Two or Three), the textbox below the dropdown list must allow user to type any text in it; but when user chooses Four, textbox should be disabled.

Here is my code

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
    var $inputs = $('#myclass');
        $('#select').change(function(){
        $inputs.prop('disabled', $(this).val() === '4');
    });
</script>
<title>Choose one</title>
</head>
<body>
    <select id="select">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
    <input type="text" id="myclass"/>
</body>
</html>

The code above is not working. Can anyone help me to solve this problem?

The DOM isn't ready :

$(function() {
    $('#select').on('change', function(){
        $('#myclass').prop('disabled', this.value == '4');
    });
});

Your JavaScript code is being executed before the DOM is rendered.

Quick fix : place your JavaScript code at the end of the <body> tag. Like this:

<!DOCTYPE html>
<html>
<head>
<title>Choose one</title>
</head>
<body>
    <select id="select">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
    <input type="text" id="myclass"/>
    <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
    <script>
        var $inputs = $('#myclass');
        $('#select').change(function(){
           $inputs.prop('disabled', $(this).val() === '4');
        });
    </script>
</body>
</html>

Another option is making JavaScript code to be executed when document is ready, but the "Quick fix" approach is quite popular nowadays. This would be the different (classical?) approach:

<script>
    $(document).ready(function () {
        var $inputs = $('#myclass');
        $('#select').change(function(){
           $inputs.prop('disabled', $(this).val() === '4');
        });
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM