Reputation: 12561
So I am getting some buttons as follows:
var reportFilterButtons = $('input[name=reportfilter]', '#reportChartForm');
Later on this easily allows me to attach a change handler as follows:
reportFilterButtons.change(handlers.reportFilterButtonsChange);
Inside of this handler I need to get the value of the currently checked button, so I do this:
var checkedReportFilterButton = $('input[name=reportfilter]:checked', '#reportChartForm');
....
if (checkedReportFilterButton.val() ....
The reportFilterButtons
and checkedReportFilterButton
selectors seem redundant however. Is there a way to get the checked/value by working against reportFilterButtons
and not doing the second selection?
Upvotes: 1
Views: 76
Reputation: 191976
A jQuery event listener handler this
property points to the element that was the target of the event. This means that you don't have to find it again. Just wrap in a jQuery object $(this), and you're good to go (fiddle demo).
Code:
<div id="reportChartForm">
<input type="radio" name="reportfilter" value="1">
<label>Radio 1</label>
<input type="radio" name="reportfilter" value="2">
<label>Radio 2</label>
<input type="radio" name="reportfilter" value="3">
<label>Radio 3</label>
</div>
var reportFilterButtons = $('input[name=reportfilter]', '#reportChartForm');
reportFilterButtons.change(reportFilterButtonsChange);
function reportFilterButtonsChange() {
var value = $(this).val(); // this is the reference to the element
console.log(value);
}
Upvotes: 1
Reputation: 64657
You could use $.filter
to find the checked one:
reportFilterButtons.filter(':checked').val()
Upvotes: 2