How to determine state of radio box triggered by another element in Jquery?
So the deal is that i update radiobox elements by clicking on div elements. So for example i have 3 divs and there's 1 radio box inside each div.
When you click on div the radio box gets checked, but problem is that this way .change() event d开发者_运维问答oes not work.
How would i get result where i know when particular radiobox has lost :checked status?
Here is code that i currently have:
$('#payment_method_cards, #payment_method_ibank_swe, #payment_method_bp').click(function(){ $(this).children('input[name="payment_method"]').attr('checked','checked'); $('input[name="payment_method"]').change(function(){ if($(this).val() == 'bp'){ alert("Thats the one"); } } });
The radiobox change only triggered if i click inside radiobox but not when on div.
I'm assuming you have an event handler tied to the div
that triggers click
or adds the checked
attribute. Why not trigger the change()
function manually after changing the state of the radio button?
$("#check-me").bind("click", function() {
$("#radio-btn1").click().change();
// change radio button state, then trigger 'change' event.
});
Update: With the code you provided, you would do something like this (updated again due to comment from OP):
$('#payment_method_cards, #payment_method_ibank_swe, #payment_method_bp').click(function(){
var $radio = $(this).children('input[name="payment_method"]');
if (!$radio.is(":checked")) {
$radio.attr('checked','checked').change();
}
});
You should define the change
handler outside the click
handler:
$('input[name="payment_method"]').change(function(){
if($(this).val() == 'bp'){
alert("Thats the one");
}
}
Use labels instead of the DIVs:
<label> <input type="radio" value="1"> Male </label>
In the above example, clicking on the word "Male" will trigger the change event.
I recommend using labels, but if you insist on using DIVs, this code will work for you. The change event is triggered only if the radio box was not checked beforehand.
$('#payment_method_cards, ...').click(function(){
var radio = $(this).children('input[name="payment_method"]');
if ( !radio[0].checked ) {
radio.attr('checked', true).change();
}
});
精彩评论