Babu
Babu

Reputation: 455

HTML radio button is not selected using jQuery/Ajax

I have a popbox box with HTML form which is showing all user information to appropriate HTML filed from db based on id using jQuery/Ajax.

Now all form field is fill up but radio button is not selected. It should be selected based on a condition like..if kittype == 1 then select first one otherwise second one.

<td>Kittype</td>
<td>
<input type="radio" name="kittype" value="1"/> &nbsp; Electronic Kit Only <br/>
<input type="radio" name="kittype" value="2" /> &nbsp; Post a Hard Copy as 
well<br/>   
</td>

Jquery/Ajax Code:

function myfunc1(id) {
        id = id;
        $.ajax({        
                url: 'edit_user_details.php',
                type: 'post',             
                data: {'id' : id},
                dataType : 'json',
                success: function( res ) {
                    console.log(res);
                    $.each( res, function( key, value ) {
                        console.log(key, value);
                        $('input[type=text][name='+key+']').val(value);
                        $('textarea[name='+key+']').val(value);

                        if ( res.kittype == 1 ) {
                            $('input[type=radio][name='+kittype+']').attr('checked', 'checked');

                        }

                    });




                }            
        });
    }

Upvotes: 0

Views: 580

Answers (4)

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

USe prop() instead of attr().

Also you can use :first or eq(0) for getting the first element.

if (res.kittype == 1) {
    $('input[type=radio][name=kittype]:first').prop('checked', 'checked');
    $("input").is(':checked');
} else {
    $('input[type=radio][name=kittype]:not(:first)').prop('checked', 'checked');

}

Upvotes: 1

Carson Ip
Carson Ip

Reputation: 1946

Why not simply write

$('input[type=radio][name=kittype][value='+res.kittype+']').prop('checked', 'checked');

Demo here

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21676

Use double quotes as

$('input[type=radio][name="kittype"]').attr('checked', 'checked');

Demo

Upvotes: 0

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

Use prop method of jquery.

$('input[type=radio][name='+kittype+']').prop('checked', true);

Upvotes: 0

Related Questions