onchange禁用textarea php

时间:2012-03-17 10:23:51

标签: javascript

这是我的表单,如果选择了city2选项,我需要禁用textarea,如果选择了其他选项,则需要启用textarea。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
var citySelect = document.getElementById('city'),
    descriptionTextarea = document.getElementById('description');

citySelect.addEventListener('change', function() {
    descriptionTextarea.disabled = citySelect.selectedIndex == 1;
}, false);
</script>
</head>
<body>
<form method="post" name="areaform" id="areaform">
<select name="city" id="city">
<option value="city1">city1</option>
<option value="city2">city2</option>
<option value="city3">city3</option>
</select><br />
<br />

<textarea name="description" id="description" cols="" rows="" style="width:150px; height:50px;"></textarea>
</form>
</body>
</html>

我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果用数字指数比较就好了......

var citySelect = document.getElementById('city'),
    descriptionTextarea = document.getElementById('description');

citySelect.addEventListener('change', function() {
    descriptionTextarea.disabled = citySelect.selectedIndex == 1;
}, false);

jsFiddle

如果您想与每个选项的value属性进行比较......

var citySelect = document.getElementById('city'),
    descriptionTextarea = document.getElementById('description');

citySelect.addEventListener('change', function() {
    descriptionTextarea.disabled = citySelect.options[citySelect.selectedIndex].value == 'city2';
}, false);​

jsFiddle

同样注意&lt; IE9不支持addEventListener(),只支持attachEvent()。您需要定义两者或使用辅助函数。

如果你最终使用jQuery,它可以更简洁......

var descriptionTextarea = $('#description');
$('#city').change(function() {
   descriptionTextarea.prop('disabled', $(this).val() == 'city2');
});

jsFiddle

答案 1 :(得分:0)

使用jQuery,您可以执行以下操作:

$.ready(function() {
  $('#city').on('change', function() {
    if ($('#city').val() == 'city2')
    {
      $('#description').attr('disabled', 'disabled');
    } else {
      $('#description').attr('disabled', '');
    }
  });
});

答案 2 :(得分:0)

使用javascript函数

<form method="post" name="areaform" id="areaform">
<select name="city" id="city" onchange="checkCity();">
<option value="city1">city1</option>
<option value="city2">city2</option>
<option value="city3">city3</option>
</select><br />
<br />

<textarea name="description" id="description" cols="" rows="" style="width:150px; height:50px;"></textarea>
</form>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function checkCity() {
    ct = $("#city option:selected").val();
    if(ct=="city2") {
        document.getElementById("description").disabled=true;
    }else{
        document.getElementById("description").disabled=false;
    }
}
</script>