jquery - 如何通过 HTML 和 JQUERY 中的选项正确禁用和启用输入字段

标签 jquery html forms

如何使用 jquery 正确禁用和启用表单元素。单击“剩余”选项时,我需要启用输入(“#byremaining”)。当我单击其他选项时,应再次禁用输入(“#byremaining”)。

<html>

    <head>
    <script src="jq.js"></script>

    <script> 
    $(document).ready(function() {
    $('#byremaining').attr('disabled','disabled');
    });

    $(function(){

    $('#remaining').click(function(){
        $('#byremaining').removeAttr('disabled');
    });

    });
    </script>

    </head>
    <body>
    Sort by:
    <select name="plaats" id="plaats">
        <option value="plaats1">plaats1</option>
        <option value="plaats2">plaats2</option>
        <option value="plaats3">plaats3</option>
        <option value="plaats4">plaats4</option>
        <option value="remaining" id="remaining">remaining</option>
    </select>
    <br/>
    date range:<br/>

    Remaining:<input type="text" value="" name="byremaining" id="byremaining"></input><br/>

    </body>

    </html>

remove 属性现在不起作用,我还没有再次创建 disabled。

最佳答案

$(document).ready(function() {
  $('#byremaining').prop('disabled', true); //use prop

  $('#plaats').change(function() {
    var selected = $('option:selected', this).attr('id')
    if (selected == 'remaining') { //if selected option is remaining 
      $('#byremaining').prop('disabled', false); //use prop
    } else {
      $('#byremaining').prop('disabled', true); //use prop
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sort by:
<select name="plaats" id="plaats">
  <option value="plaats1">plaats1</option>
  <option value="plaats2">plaats2</option>
  <option value="plaats3">plaats3</option>
  <option value="plaats4">plaats4</option>
  <option value="remaining" id="remaining">remaining</option>
</select>
<br/>date range:
<br/>Remaining:

<input type="text" value="" name="byremaining" id="byremaining"></input>
<br/>

  1. 为选择使用更改事件
  2. 使用.prop()

关于jquery - 如何通过 HTML 和 JQUERY 中的选项正确禁用和启用输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295292/

相关文章:

php - 如何在 URL 上发送 AJAX 请求

javascript - Jquery 完成回调倒计时

html - 可以使用 WAI-ARIA 链接角色将任何元素变成超链接吗?

javascript - 如何从 QML 调用 HTML 函数

javascript - 禁用启用提交按钮 - 禁用直到所有字段都有值 - HTML 表单检查所有输入的答案

jQuery 恢复文本框默认值

javascript - 在 Javascript 中为 Dreamweaver 或其他编辑器指定可选参数和多态性提示

javascript - 禁用输入类型=数字的输入验证

php - Ajax 更新 HTML 元素的 css

javascript - 如何重置 bsDatepicker 输入?