Steve Brown
Steve Brown

Reputation: 115

Using Json how can I select a radio button based on value in my database?

Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?

FORM

<form action="#">

<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>

<button id="submit-id">Prefill Form</button>

<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">

<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />

<button id="submit-form" name="Submit-form" type="submit">Submit</button>


</form> 

SCRIPT

<script>
     $(function(){


        $('#submit-id').on('click', function(e){  // Things to do when 

.......

.done(function(data) {

    data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);

});
        });
     });
</script>

/tst/orders2.php

<?php

    // Create the connection to the database
    $con=mysqli_connect("xxx","xxx","xxx","xxx");


........


        while ($row = mysqli_fetch_assoc($result)) 
            {
     echo json_encode($row);
     die(); // assuming there is just one row
        }
    }
    ?>

Upvotes: 0

Views: 3286

Answers (4)

Lyndsey Browning
Lyndsey Browning

Reputation: 221

You currently have both radio buttons using the same ID. ID's should be unique.

You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:

 $('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);

Upvotes: 1

jogesh_pi
jogesh_pi

Reputation: 9782

Don't use ID because you have same ID of both radio buttons

done(function(data) {

  data = JSON.parse(data);
  $('#txt1').val(data.txt1);
  $('#txt2').val(data.txt2);

  // Don't use ID because the name of id is same
  // $('#q1').val(data.q1);
  var $radios = $('input:radio[name=q1]');
  if($radios.is(':checked') === false) {
    $radios.filter('[value='+data.q1+']').prop('checked', true);
  }

  });

Upvotes: 1

Frebin Francis
Frebin Francis

Reputation: 1915

you can refer the following link to solve your problem. works fine for me

JQuery - how to select dropdown item based on value

Upvotes: 0

Dale
Dale

Reputation: 10469

You can do it based on the value of said input:

instead of

$('#q1').val(data.q1);

Try

$('input:radio[value="' + data.q1 + '"]').click();

On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE

Upvotes: 0

Related Questions