当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: