input field disabled until radio button is checked (HTML)

痴心易碎 提交于 2019-12-03 16:42:29

问题


I have two fields, one of them is a text input field and the other is a select tag. The thing is I want one of them to be enabled only and the user should choose which one is enabled by clicking on one of the radio buttons above.

So if the user chooses the first radio button the input field will be enabled and if he choose the second one the select tag will be enabled.

Here's my code:

        <input type="radio" name="type" value="customurl">wanna custom url?
        <input type="text" name="custom" placeholder="should be 5 charecters at least" >
        <br><br>
        <input type="radio" name="type" value="customurl">random?
        <select name="charstype">
            <option>Letters</option>
            <option>Number</option>
        </select>

回答1:


You will need to use javascript. The shortest way in code you gave would be to attach an ID attribute both to select and input field, and disable/enable them by "onclick" event.

<input onclick="document.getElementById('custom').disabled = false; document.getElementById('charstype').disabled = true;" type="radio" name="type" checked="checked">wanna custom url?
<input type="text" name="custom" id="custom" placeholder="should be 5 charecters at least" >
<br><br>
<input onclick="document.getElementById('custom').disabled = true; document.getElementById('charstype').disabled = false;" type="radio" name="type" value="customurl">random?
<select name="charstype" id="charstype" disabled="disabled">
       <option>Letters</option>
       <option>Number</option>
</select>



回答2:


I modified your code to do what you want, here it is:

<input type="radio" name="type" value="customurl" 
onclick="document.getElementById('text').removeAttribute('disabled')">wanna custom url?
<input type="text" id="text" name="custom" 
placeholder="should be 5 charecters at least" disabled>
<br><br>
<input type="radio" name="type" value="customurl" 
onclick="document.getElementById('sel').removeAttribute('disabled')">random?
<select id="sel" name="charstype" disabled>
    <option>Letters</option>
    <option>Number</option>
</select>​​​​​​​​​​​

you can see it working here



来源:https://stackoverflow.com/questions/12491297/input-field-disabled-until-radio-button-is-checked-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!