e-Designary e-Designary - 2 months ago 9
HTML Question

How to set the value for radio button while editing using jQuery?

I've a radio button in my form and when I enter a reference number, I can fetch the corresponding form details along with source value using jQuery. I don't know how to set that value to radio button. Thank You!

<input type="radio" ng-model="selected" name="source" class="source" <?php echo ($row['source']=='VAT')?'checked':'' ?> value="VAT">VAT
<input type="radio" ng-model="selected" name="source" class="source" <?php echo ($row['source']=='CST')?'checked':'' ?> value="CST">CST


jQuery

$('#gp_no').on('keypress', function(e){
if(e.keyCode === 13)
{
$(this).trigger("enterKey");
var val = $(this).val();
var dataString = "gp_no=" + val;
$.ajax({
type: "POST",
url: "post_process.php",
data: dataString,
dataType: 'json',
success: function(data){
$('.source').val(data.source);
}
});
}
});


post_process.php

if(ISSET($_POST['gp_no'])) {

$gp_no = $con->real_escape_string($_POST['gp_no']);

$query = "SELECT * FROM items WHERE items.gp_no = $gp_no";

if ($result = $con->query($query)) {
$row = $result->fetch_assoc();
$source = $row['source'];
}
$json = array($vehicle_no, 'source' => $source);
$json = json_encode($json);
echo $json;
}

Answer

If you are looking to get the value of a selected radio button you can do this:

$('input[name="source"]:checked').val()

When you get the response from your ajax call you check your button:

First change this:

<input type="radio" ng-model="selected" name="source" class="source" id="VAT" value="VAT">VAT
<input type="radio" ng-model="selected" name="source" class="source" id="CST" value="CST">CST

$("#"+data.source).prop("checked", true)

This assune that your returned value is VAT or CST