我想要这个:当用户单击单选按钮标签时,它将自动单击单选按钮本身。目前,如果用户单击单选按钮后面的标签,则不会发生任何事情,从而迫使用户单击微小的单选按钮本身。
有些人建议在标签上使用“for”属性,但为此我需要更改第二个选项的“id”;通过这样做,表单将发布两个已选中的选项,因此它在我的情况下不起作用。
https://jsfiddle.net/j4qzh544/2/
这是 html :
<form href="#">
<input type="radio" id="option1" name="option1" data-label="Option one" value="1"><label class="radio-label">Option one</label>
<input type="radio" id="option1" name="option1" data-label="Option two" value="2"><label class="radio-label">Option two</label>
<input type="submit"/>
</form>
为了实现这一点,我尝试使用 Jquery 在每个带有“radio-label”类的标签上创建一个单击方法,单击其单选按钮。类似于下面的代码,但它不起作用:
$('.radio-label').each(function (i) {
$(this).previous().click();
});
最佳答案
使用 for
<label>
的属性.
The ID of a labelable form-related element in the same document as the label element. The first such element in the document with an ID matching the value of the for attribute is the labeled control for this label element.
<label for="option2" class="radio-label">Option two</label>
<input type="radio" id="option1" name="option1" data-label="Option one" value="1"><label for="option1" class="radio-label">Option one</label>
<input type="radio" id="option2" name="option1" data-label="Option two" value="2"><label for="option2" class="radio-label">Option two</label>
关于javascript - 单击标签使单击单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45328309/