0

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
        }
    }
    ?>

4 Answers 4

1

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);
  }

  });
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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

Comments

0

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

JQuery - how to select dropdown item based on value

1 Comment

Except that we're talking about radios

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.