Parminder
Parminder

Reputation: 191

Add click event using jQuery to radio buttons with name property

I have a code and it has lots of tr tags like the following and I want to add onclick event dynamically to the radio buttons in them...

<tr class="main3" id="2aiv">
    <td>iv. Hb</td>
    <td>Yes<input type="radio" name="2aiv" value="1" /></td>
    <td>No<input type="radio" name="2aiv" value="0" /></td>
</tr>

In a function if some condition is true I use the following code to add a class to tr tag

$('#2aiv').addClass('notAns');

which results to the following (this is working fine)

<tr class="main3 notAns" id="2aiv"> .... </tr>

the problem is when I try to use the following is does nothing...

$('input[name^=2aiv]').click(removeCls('2aiv')); 

function removeCls(id)
{
   $('#'+id).removeClass('notAns');
}

Actually I want to add an onclick event on radio button i.e. when they are clicked if notAns class is present in parent tr tag is should be removed

Upvotes: 0

Views: 1696

Answers (4)

Jitendra Yadav
Jitendra Yadav

Reputation: 896

Try this one:

<table>
    <tr class="main3 notAns" id="2aiv">
        <td>iv. Hb</td>
        <td>Yes<input type="radio" name="2aiv" value="1" /></td>
        <td>No<input type="radio" name="2aiv" value="0" /></td>
    </tr>
    </table>

    $(document).ready(function(){

        $('input[name^=2aiv]').click(function(){

            removeCls('2aiv');

        });

    });
    function removeCls(id)
    {
       $('#'+id).removeClass('notAns');
    }

DEMO

Upvotes: 0

Jay
Jay

Reputation: 137

Try to use .change() instead of using .click()

    $('input[name^=2aiv]').change(function() {
//Your function

});

Upvotes: 0

Dwza
Dwza

Reputation: 6565

your

$('#2aiv').addClass('notAns');

and

function removeCls(id)...

actually work

took your code, did a view changes and added it to a jsfiddle

JSFIDDLE

actually it adds a class and it removes it after clicking a radio

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You are missing syntax to bind event, need to add function() and then call removeCls inside it.

Change this

$('input[name^=2aiv]').click(removeCls('2aiv')); 

to

$('input[name^=2aiv]').click(function(){removeCls('2aiv');}); 

Upvotes: 1

Related Questions