Radio Groups with clickable label

2020-06-07 04:14发布

问题:

From what I have gathered, in order to make a label of a radio button clickable, you must assign the same "name" attribute value to both elements.

The problem I am having is when you have more than one radio button, say a "yes or no" type selection. In order to make it to where if you click one, the other disables is that both radio buttons "name" attribute has to be the same value.

Is it possible to do both?

<label for="no">No</label> 
<input type="radio" name="no" value="no" />

<label for="yes">Yes</label> 
<input type="radio" name="yes" value="yes" />

回答1:

id (not name) attribute should be referred by label's for attribute. It should be like this: http://jsfiddle.net/zzsSw/

<label for="no">No</label> 
<input type="radio" name="mygroup" id="no" value="no" />

<label for="yes">Yes</label> 
<input type="radio" name="mygroup" id="yes" value="yes" />


回答2:

You can also write labels without IDs:

<label>
  <input type="radio" name="mygroup" />
  My clickable caption
</label>

or checkbox

<label>
  <input type="checkbox" name="mygroup[]" />
  My clickable caption
</label>