Toggle HTML radio button by clicking its label

JavascriptHtmlRadio Button

Javascript Problem Overview


Is there please a simple way to make a radio button toggle - when a text near it is clicked - without introducing any big Javascript Framework into my smal PHP project?

The web form looks like this:

<html>
<body>
<form method="post">
<p>Mode:<br /> 
<input type="radio" name="mode" value="create"><i>create table</i><br />
<input type="radio" name="mode" value="select" checked>select records (can specify id)<br />
<input type="radio" name="mode" value="insert">insert 1 record (must specify all)<br />
<input type="radio" name="mode" value="delete">delete records (must specify id)<br />
<input type="radio" name="mode" value="drop"><i>drop table</i><br />
</p>
<p>Id: <input type="text" name="id" size=32 maxlength=32 /> (32 hex chars)</p>

<p>Latitude: <input type="text" name="lat" size=10 /> (between -90 and 90)</p>
<p>Longitude: <input type="text" name="lng" size=10 /> (between -90 and 90)</p>
<p>Speed: <input type="text" name="spd" size=10 /> (not negative)</p>
<p><input type="submit" value="OK" /></p>
</form>
</body>
</html>

Javascript Solutions


Solution 1 - Javascript

You can also wrap your elements without giving them each an ID, since a <label> is implicitly for the input it contains, like this:

<label>
   <input type="radio" name="mode" value="create">
   <i>create table</i>
</label>

Solution 2 - Javascript

You can use <label> elements, which are designed to do exactly that:

<input type="radio" id="radCreateMode" name="mode" value="create" />
<label for="radCreateMode"><i>create table</i></label>

Solution 3 - Javascript

Wrapping the input under the label should work.

<label>
    <input type="radio" name="mode" value="create"><i>create table</i>
</label>

Solution 4 - Javascript

I had trouble finding the value of the radio button using this method, an alternative is to use a hit area https://stackoverflow.com/questions/19246893/increasing-clickable-area-of-a-button.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander FarberView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptFrédéric HamidiView Answer on Stackoverflow
Solution 3 - JavascriptJason ChingView Answer on Stackoverflow
Solution 4 - JavascriptChristopher GriggView Answer on Stackoverflow