Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input field disabled until radio button is checked (HTML)

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>
like image 617
Alex C. Avatar asked Sep 19 '12 08:09

Alex C.


People also ask

How do I restrict radio buttons in HTML?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .


2 Answers

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>
like image 148
Wilq Avatar answered Oct 19 '22 19:10

Wilq


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

like image 36
Nelson Avatar answered Oct 19 '22 18:10

Nelson