I am writing a basic web app, this has some list elements that I need to be able to click on the entire LI that surrounds each one to select the radio button held within, and only ensure the one I have clicked is selected. I can do this writing the code within the .click callback, however if I try to call the same code from a named function it falls down, I believe this is something to do with the “this” reference I am using, however I cannot seem to fix it.
The HTML is
<ul>
<form id="healthCheckAge" name="healthCheckAge">
<li> <input type="radio" name="eighteen" value="18-30" />18-30 </li>
<li> <input type="radio" name="thirtyone" value="31-45" />31-45 </li>
<li> <input type="radio" name="fourtysix" value="46-65" />46-65 </li>
<li> <input type="radio" name="sixtyfive" value="65+" />65+</li>
</form>
</ul>
And the JavaScript is
function li_click(){
//set the vars for the selectors
var listInputs = $('#healthCheckAge li input');
var clicked = listInputs.attr('name');
//loop on all the li children to see if they match the clicked LI - if not ensure that they are unchecked and faded
$(listInputs).each(function(index,Element){
$(listInputs).attr('checked',false).parent().addClass('selected');
});
//set the radio button to checked and apply a style to it, while removing this from any other checked radio buttoon
if($(listInputs).attr('name')==clicked){
$(this).children().attr('checked','true').parent().removeClass('selected');
}
}
$('#healthCheckAge li').click(function(){
li_click();
});
I think the problem is that when I call the very last conditional statement the ‘this’ is not reflecting what I need.
Any ideas?
Just pass the element to the function:
Inside the click handler,
thisrefers to the element, but insidelolit points to the owner of the function, which is the globalwindowobject.