BaddieProgrammer
BaddieProgrammer

Reputation: 115

Set radio button to checked based on returned JSON from MySQL database

One of my whacky forms need to be populated automatically when I select a value from a . This is all done using $.ajax and PHP and JSON. So far most the the HTML controls get populated without any problem except for one special type of control- the radio button. I'm trying to set a radio button in my HTML form to checked state in a radio button group, based on what MySQL returned in JSON.

In MySQL I store radio button state value as 0 or 1 integers for yes or no.

The column name for radio button state in the database is subscribe_status. The form name of the radio button HTML control is subscribe-status(I'll change that to remove confusion later on).

What happens at the moment is ... nothing. I'm not sure why.

jQuery to change radio button state:

// property defined?
if(output[0].subscribe_status !== undefined){
    // none of radio buttons are checked?
    if($('input[name=subscribe-status]').is(':checked') === false) {
        // check one based on returned JSON
        if(output[0].subscribe_status === 0){
            $('input[name=subscribe-status]').filter('[value=0]').prop('checked', true);
        }else if(output[0].subscribe_status === 1){
            $('input[name=subscribe-status]').filter('[value=1]').prop('checked', true);
        }
    }
}else{
    console.log("Subscribe status property is undefined");
}

I perform these inside success of $.ajax call and it works for other HTML controls like inputs of type <text>, <textarea> and <select>, but not radio buttons. MySQL results are stored into output variable as Object.

HTML form:

<div class="form-group">
    <label for="subscribe-status" class="sr-only">Subscribed?:</label>
    <label for="subscribe-status">Subscribed?:</label>
    <div class="radio-inline">
        <label for="subscribe-status"><input type="radio" name="subscribe-status" value="1" />Yes</label>
    </div>
    <div class="radio-inline">
        <label for="subscribe-status"><input type="radio" name="subscribe-status" value="0">No</label>
    </div>
</div>

Note: I use Bootstrap.

Upvotes: 0

Views: 3643

Answers (2)

Tushar
Tushar

Reputation: 87203

No need of if...else:

$('input[name="subscribe-status"][value="' + output[0].subscribe_status + '"]').prop('checked', true);

This will select the input element with name attribute as subscribe-status and having value as output[0].subscribe_status value.

Make sure your output variable if JSON and it contains subscribe_status.

Upvotes: 4

depperm
depperm

Reputation: 10746

You have an error here

$("input[name=subscribe-status]')

you start with a double quote and end with a single.

Upvotes: 1

Related Questions