Home > Back-end >  Only being able to choose one option between a radio button and a textbox in HTML
Only being able to choose one option between a radio button and a textbox in HTML

Time:09-24

I'm making a form for a landing page and I've given two radio options for gender (male and female) and I've given space for someone to write another gender as a textbox, but it's still possible to click both male and have an answer in the textbox. How do I make this not possible?

So far, I've given each element a name (gender) so that the computer knows they belong to the same family, this worked for radio buttons but not the textbox.

This is what it looks like:

Code The Page

CodePudding user response:

Incase of radio buttons, atleast one of them have to be selected. In your case, you can add a third radio button for other and a text box next to it. Disable the text box when the male or female radio buttons are selected. If the third radio button(other) is selected, enable text entry in the text box. I hope this helps answer your question.

CodePudding user response:

Maybe Try adding some JS. Radio button seems fine not sure why they don't work.

Here's something which you can do. : https://codepen.io/akpose/pen/rNwZEaP

<input type="radio" onclick="disableGenderButton()" name="Gender" value="Female" required> Male <br><input type="radio" onclick="disableGenderButton()" name="Gender" value="Female" required> Female  <br>
<input type="radio" onclick="enableGenderButton()" name="Gender" value="Other" required> Other  
<input type="text" id="GenderText" name="GenderText" disabled>

<script>
function disableGenderButton(){
document.getElementById("GenderText").disabled = "true";
}
function enableGenderButton(){
document.getElementById("GenderText").disabled = "";
}
</script>

CodePudding user response:

.othergender {
  width: 10%;
}
<!doctype html>
    <html>
    <head>
        <title>Register</title>
        <h1>Registration page</h1>
    </head>
    <body>
        <p>Please register here</p><br>
        <form>
            First name: <input type="text" required id="FirstName"><br>
            Last name: <input type="text" required id="LastName"><br>
            <input type="button" value="Submit Form"><input type="reset"><br>
                Gender: <input type="radio" required name="gender">
                Male<input type="radio" required name="gender">
                Female&nbsp;<input type="radio" required name="gender">
                <input type="text" required value="other" class="othergender" name="gender">
            <input type="submit">
        </form>
    </body>
    </html>

  • Related