input field disabled until radio button is checked (HTML)

Alex C. picture Alex C. · Sep 19, 2012 · Viewed 47.6k times · Source

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>

Answer

Wilq picture Wilq · Sep 19, 2012

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>