简体   繁体   English

禁用/启用基于选择Javascript的无线电/选择选项的文本框

[英]Disable/Enable a text box based on radio/select option selected Javascript

I am trying to disable an input field in HTML if a radio button has a particular value. 我试图在单选按钮具有特定值时禁用HTML中的输入字段。 I have used Javascript functions for the same. 我已经使用了相同的Javascript函数。

CODE SNIPPET 1 : (HTML RADIO BUTTON) 代码SNIPPET 1 :( HTML RADIO BUTTON)

<div class="element-radio">
    <label class="title">Children</label>
    <div class="column column2">
        <label>
            <input type="radio" name="children" value="Yes" onChange="findselected()"/>
            <span>Yes</span>
        </label>
    </div>
    <span class="clearfix"></span>

    <div class="column column2">
        <label>
            <input type="radio" name="children" value="No" checked="checked" onChange="findselected()"/>
            <span>No</span>
        </label>
    </div>
    <span class="clearfix"></span>
</div>

<div class="element-number">
    <label class="title">No of children</label>
    <div class="item-cont">
        <input class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />
        <span class="icon-place"></span>
    </div>
</div>

CODE SNIPPET 2 : (JAVASCRIPT FUNCTION) 代码SNIPPET 2 :( JAVASCRIPT FUNCTION)

<script type="text/javascript">
function findselected() { 
   if (document.form.children.value == 'No') {
      document.form.no_children.disabled=true;
//      return false;  // not sure this line is needed
   } else {
      document.form.no_children.disabled=false;
//      return false;  // not sure this line is needed
   }
} 
</script>

This does not work in the required way. 这不能按要求的方式工作。 Is there a better way to go about doing the same? 有没有更好的方法去做同样的事情? I'm fairly new to Javascript so I wouldn't be able to implement a complicated code. 我是Javascript的新手,所以我无法实现复杂的代码。

Update your script with the following code: 使用以下代码更新脚本:

function findselected() { 
    var result = document.querySelector('input[name="children"]:checked').value;
    if(result=="Yes"){

        document.getElementById("inputtext").setAttribute('disabled', true);
    }
    else{
        document.getElementById("inputtext").removeAttribute('disabled');
    }
}

And add id attribute in your input control as id="inputtext" . 并在输入控件中添加id属性为id="inputtext"

<input id="inputtext" class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />

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

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