How to Use the "Required" Attribute With a "Radio" Input Field

How to use the required attribute with a radio input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

<form>  Select Gender:<br>
<label> <input type="radio" name="gender" value="male" required> Male </label><br>
<label> <input type="radio" name="gender" value="female"> Female </label><br>
<label> <input type="radio" name="gender" value="other"> Other </label><br>
<input type="submit"></form>

Using the required attribute with dynamically generating radio-buttons

The problem

I solved the problem of making mandatory to select one of the answers to the test questions, with the help of my wife, using what I would call an example of Lateral Thinking.

that is to say, by not operating on the mandatory nature of the selection but on the effects of its lack. In few words: If you don't select an answer you don't go ahead and you don't need any "required".

How

I set the initial score value to 10 (score not reachable on the first question or later) which operates as a block.

 score = 10;

if the user selects the first answer the maximum value he can reach is 4 and goes to the next question. For each question the user has "score = 10", and must lower it by clicking on an answer.

if (score <10) {
score_all = score_all + score;
else {// rendering error message
get ("message"). innerHTML = "<i>" + "Please select your answer." + "</i>";
}
}

The selected answers are summed in:

score_all = score_all + score;

HTML5: How to use the “required” attribute with a radio button with image?

Setting display: none causes the "required" popup to be hidden.

Instead, you could try absolute positioning with a minuscule zoom:

#invisible input[type="radio"] {
position: absolute;
zoom: 0.1;
}

JSBin

Add required attribute when radio is checked

According to this answer, you have to monitor the change on both radio inputs. So move your javascript script after the second radio.

Also there was missing a )

Fiddle updated: http://jsfiddle.net/fhfrzn1d/1/

$('input[name="price"]').change(function () {
if($("#value_radio").is(':checked')) {
$('#value_input').attr('required', true);
} else {
$('#value_input').removeAttr('required');
}
});


Related Topics



Leave a reply



Submit