Reputation: 7493
I want to get the element of a radio button by using its associated label name.
I know the inner HTML of the label will always be the same. However, the id
and value
of the radio button will change. The inner HTML for the label will always be "Agent".
Can I use that to get the radio button element using jQuery? If so, how?
<input id="ctl00_ctl00_MainContent_ContentPlaceHolder_realRole_14" type="radio" name="ctl00$ctl00$MainContent$ContentPlaceHolder$realRole" value="85" checked="checked">
<label for="ctl00_ctl00_MainContent_ContentPlaceHolder_realRole_14">Agent</label>
Upvotes: 0
Views: 58
Reputation: 770
You can loop over your input elements, get their IDs and check for labels for that ID. Then validate the text of the label:
$('input[type=text]').each(function(){
var label = $('label[for="' + $(this).attr('id') + '"]');
if(label.text() === 'Agent') {
console.log('Found input id for Agent label!');
}
})
http://jsfiddle.net/d3fhumj8/1/
Upvotes: 1
Reputation: 54831
First get for
attribute of a label
var id = $('label:contains("Agent")').attr( "for" );
Then use this value as id
var checkbox = $( "#" + id );
Upvotes: 1