user7066345 user7066345 - 1 month ago 6
Javascript Question

Why isn't this jquery event handler wiring up as expected?

I have a radio button list with a name of "ReportTypeId". For each

radio
button I want to display an alert with its value when it's clicked.

I wrote the following jQuery which gets all 5 radio buttons the list with a name of "ReportTypeId":

$("[name='ReportTypeId']").toArray().forEach(function(reportTypeId){
reportTypeId.click(function(reportTypeId){
alert(reportTypeId.value);
});
});


When I set a breakpoint and examine tthe variables at load time the variables look as expected. However, when I click on a radio button after page load nothing happens. What I am doing wrong in the jquery above?

Answer

You should be using this to get the current element inside of your callback function to .click(). The argument passed to function is actually the click event object.

$("[name='ReportTypeId']").toArray().forEach(function(reportTypeId){
    reportTypeId.click(function(event){
        alert(this.value);
    });
});

You can simplify your code a lot simply by calling .click() on the jQuery collection. The event listener will automatically be attached to all the elements in the collection.

$("[name='ReportTypeId']").click(function(event){
    alert(this.value);
});