yejinxin
yejinxin

Reputation: 596

Cannot get the checked radio correctly in click event

Page code as below:

<input type="radio" class="direct" name="r1" value="first" />
    <span class="proxy">radio1</span>
<input type="radio" class="direct" name="r1" value="second" />
    <span class="proxy">radio2</span>

js code as below:

$('.direct').click(function(e) {
    var obj = $(this).parent(),
        value = obj.find('input:checked').val();
    if(value){
        alert('you click ' + value + ' button');
    }else{
        alert('you did not click a button');
    }
});
$('.proxy').click(function(e) {
    $(this).prev().click();
});​

Here is the example on JSFiddle

My question is:
why clicking on span text does not work like clicking directly on radio button?

Upvotes: 0

Views: 197

Answers (2)

HungryCoder
HungryCoder

Reputation: 7616

As i said earlier, question was not clear, at least for me. however, if you want to get the radio checked when clicked on next span, you can do this way:

$('.proxy').click(function(e) {
    $(this).prev().attr('checked', true)
});​

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68400

If you use a label with for attribute set to the correct input, you could avoid all this problem.

<input type="radio" class="direct" name="r1" id="r11" value="first"/>
<label class="proxy" for="r11">radio1</label>
<input type="radio" class="direct" name="r1" id="r12" value="second"/>
<label class="proxy" for="r12">radio1</label>​​​​​​​​​

DEMO

Upvotes: 2

Related Questions