Reputation: 1629
I would like radio button to check/uncheck whenever i click it's parent div. Radio buttons are originally hidden.
I was trying to achieve that by wrapping <label>
around the div. It works, but jQ.toggleClass
stops working.
HTML
<div class="big">
This is a div 1
<input id="chb" type="radio" />
</div>
<br/>
<div class="big">
This is a div 2
<input id="chb" type="radio" />
</div>
CSS
.big {
width:100px;
height:100px;
background-color:red;
cursor:pointer;
}
.hli {
border:2px solid blue;
}
/*.chb{display:none;}*/
JQ
$('.big').click(function() {
$('.hli').toggleClass('hli');
$(this).toggleClass('hli');
});
JSFIDDLE: http://jsfiddle.net/QqVCu/2/
Upvotes: 17
Views: 53785
Reputation: 4275
Tell me that if u want this: http://jsfiddle.net/QqVCu/6/
jQuery (Updated)
$('.big').click(function() {
if($(this).find('input[type="radio"]').is(':checked')){
$(this).find('input[type="radio"]').prop('checked', false);
}
else{
$(this).find('input[type="radio"]').prop('checked', true);
}
$('.hli').toggleClass('hli');
$(this).toggleClass('hli');
});
Upvotes: 3
Reputation: 820
If you want to use JQuery, this is how you should do it
$('.big').on({
click: function () {
$('.hli').toggleClass('hli');
$(this).toggleClass('hli');
}
}, 'input[name="chb"]');
Upvotes: 0
Reputation: 205997
Using a pure HTML/CSS solution:
.isHidden {
display: none; /* hide radio buttons */
}
.label {
display: inline-block;
background-color: red;
width: 120px;
height: 120px;
padding: 5px 10px;
}
.radio:checked + .label { /* target next sibling (+) label */
background-color: blue;
}
<input id="radio_1" class="radio isHidden" name="radio_a" type="radio">
<label for="radio_1" class="label">1</label>
<input id="radio_2" class="radio isHidden" name="radio_a" type="radio">
<label for="radio_2" class="label">2</label>
Upvotes: 10
Reputation: 1869
Try this:
To bypass jQuery event bubbling I've used regular JS to trigger the click().
$('.big').click(function () {
$('.hli').toggleClass('hli');
$(this).toggleClass('hli');
var Id = $(this).find('input[type=radio]').attr('id');
document.getElementById(Id).click();
});
Upvotes: 0
Reputation: 4678
How about that: http://jsfiddle.net/sgospodarets/QqVCu/5/ ? All that is necessary - wrap inputs in label. Then do not need JavaScipt.
Upvotes: 30
Reputation: 144659
you can use prop()
method, try the following:
$('.big').click(function() {
$('.hli').removeClass('hli');
$(this).addClass('hli').find('input').prop('checked', true)
});
please note that IDs must be unique and in order to work properly radio buttons should have name properties:
<input id="chb1" type="radio" name="radioGroup"/>
<input id="chb2" type="radio" name="radioGroup"/>
Upvotes: 3
Reputation: 2113
Try this: http://jsfiddle.net/ZuXvM/
To have a single radio button checked, you should group them by name (give same name for all the buttons that are part of the group)
Upvotes: 2