fmc
fmc

Reputation: 490

How do I pass DB field value to radio button using JQuery

Reading the DB using ajax, I have the following:

$('#fetch').click(function(){
    var nameid = parseInt($('#names').val());
    $.ajax({
        url       : "ws.php",
        type      : "POST",
        datatype  : "JSON",
        data      : {                           
                        editvalues  : 1,
                        id          : nameid
                    },
        success:function(show){
            $('#cr').val(show.creditrated);
        }
    });
});

And I'm trying to pass the value if creditrated to radio buttons using cr:

<div class="col-sm-2">
<?php if($row[11] == "Y") { ?>
    <input type="radio" id="cr" value="Y" checked><strong>Yes</strong>
    <input type="radio" style="margin-left: 8px" id="cr"  value="N"><strong>No</strong>
    <?php } elseif($row[11] == "N") { ?>
    <input type="radio" id="cr" value="Y"><strong>Yes</strong>
    <input type="radio" style="margin-left: 8px" id="cr"  value="N" checked><strong>No</strong>
<?php } else { ?>
    <input type="radio" id="cr" value="Y"><strong>Yes</strong>
    <input type="radio" style="margin-left: 8px" id="cr"  value="N"><strong>No</strong>
<?php } ?>
    <span class="error" style="color: red"> <?php echo $crErr;?></span>

$row[11] holds the value "Y" or "N".

I know I have these radio buttons tagged wrongly, but i don't know how to do it the right way. Can someone help me with this? Thanks.

Btw, I have 15 other fields (not shown in the ajax) that are all loading properly. This is the only one giving me a problem.

Upvotes: 0

Views: 833

Answers (1)

Abhash Upadhyaya
Abhash Upadhyaya

Reputation: 727

Try the following changes

$('#fetch').click(function(){
    var nameid = parseInt($('#names').val());
    $.ajax({
        url       : "ws.php",
        type      : "POST",
        datatype  : "JSON",
        data      : {                           
                        editvalues  : 1,
                        id          : nameid
                    },
        success:function(show){
            if(show.creditrated == "Y") {
                $("#cr_Y").prop("checked", true);
                $("#cr_N").prop("checked", false);
            }
            else {
                $("#cr_Y").prop("checked", false);
                $("#cr_N").prop("checked", true);
            }
        }
    });
});

And add name property to radio buttons linked together...

<div class="col-sm-2">
    <input type="radio" name="radioSet" id="cr_Y" value="Y"><strong>Yes</strong>
    <input type="radio" name="radioSet" style="margin-left: 8px" id="cr_N"  value="N"><strong>No</strong>
    <span class="error" style="color: red" id="crErr"></span>

Upvotes: 1

Related Questions