user7066345
user7066345

Reputation: 437

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?

Upvotes: 1

Views: 35

Answers (4)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could attach click event to all buttons in same time because they have the same name ReportTypeId, you don't need to use .forEach() and loop... then to get the value use .val() :

$("body").on('click', '[name='ReportTypeId']', function(){
     alert($(this).val());
});

Hope this helps.

$("body").on('click', '[name="ReportTypeId"]', function(){
     alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='radio' name='ReportTypeId' value='radio_1' checked/> Radio 1
<br>
<input type='radio' name='ReportTypeId' value='radio_2'/> Radio 2
<br>
<input type='radio' name='ReportTypeId' value='radio_3'/> Radio 3
<br>
<input type='radio' name='ReportTypeId' value='radio_4'/> Radio 4

Upvotes: 0

cmac
cmac

Reputation: 3268

Try this:

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

use this inside of function callback and you don't have to use toArray()

Upvotes: 0

darrylyeo
darrylyeo

Reputation: 3453

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);
});

Upvotes: 1

mojarras
mojarras

Reputation: 1634

reportTypeId.value is probably undefined and therefore, no alert will be displayed.

It is undefined because by default the first argument in the click event callback function is the event object, not the radio button itself. Try alerting this.value instead of reportTypeId.value.

Upvotes: 0

Related Questions