Given the following html:
<dt><span class="q-num">1</span>. What is one plus one?</dt>
<dd><input type="radio" value="a" name="1" required /> 4</dd>
<dd><input type="radio" value="b" name="1" required /> 7</dd>
<dd><input type="radio" value="c" name="1" required /> 2</dd>
<dd><input type="radio" value="d" name="1" required /> 8</dd>
<dt><span class="q-num">2</span>. What is two plus two?</dt>
<dd><input type="radio" value="a" name="2" required /> 4</dd>
<dd><input type="radio" value="b" name="2" required /> 7</dd>
<dd><input type="radio" value="c" name="2" required /> 2</dd>
<dd><input type="radio" value="d" name="2" required /> 8</dd>
<dt><span class="q-num">3</span>. What is three plus three?</dt>
<dd><input type="radio" value="a" name="3" required /> 4</dd>
<dd><input type="radio" value="b" name="3" required /> 7</dd>
<dd><input type="radio" value="c" name="3" required /> 2</dd>
<dd><input type="radio" value="d" name="3" required /> 6</dd>
I want to alert() the value of the nearest previous span[class='q-num'] when any input[type='radio'] is clicked. I’ve tried closest() but all I get is a blank alert..
prevUntilis your friend:Here’s the fiddle: http://jsfiddle.net/UPRBT/
If your posted markup is your real code, you can just use the
nameproperty of the clicked radio button:Here’s the fiddle: http://jsfiddle.net/b4Sj8/
A more efficient way would be to use this custom traversal method:
which you can then use like this:
Here’s the fiddle: http://jsfiddle.net/b4Sj8/1/