简体   繁体   English

根据下拉值禁用的输入标签不起作用

[英]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 : DOM尚未准备就绪:

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

Your JavaScript code is being executed before the DOM is rendered. 在呈现DOM之前,您的JavaScript代码正在执行。

Quick fix : place your JavaScript code at the end of the <body> tag. 快速修复 :将您的JavaScript代码放在<body>标记的末尾。 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. 另一种选择是使JavaScript代码在文档准备就绪时执行,但是“快速修复”方法如今非常流行。 This would be the different (classical?) approach: 这将是不同的(经典的?)方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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