Reputation: 766
I have a question. So I tried to populate the value of a textbox based on selectbox. My HTML:
<form id="form_gift" action="myAction" method="post">
<div class="form-group">
<label for="">Gift</label>
<select id="statusSelect" name="{{ form_gift.gift.name }}" class="form-control" onChange="getPrix()">
{% for key,category in form_gift.gift.choices %}
<option value="{{ key }}">
{{ category }}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label class="control-label" for="">Price</label>
<input type="text" id="{{ form_gift.prix.name }}" name="{{ form_gift.prix.name }}" value="" placeholder="" class="form-control" required="required"/>
</div>
</form>
<script>
function getPrix() {
var selectedId = $("#statusSelect option:selected").val(),
url_deploy = "http://"+window.location.hostname+"/getPrice";
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id:selectedId},
dataType: 'json',
success: function (result) {
$('#prix').val(result.Value);
}
});
}
</script>
My PHP:
public function getPrix()
{
if (isset($_POST['id']))
{
$iIdGift = $_POST['id'];
}
$o_Article = Article::find($iIdGift);
$prix = $o_Article->articlePrice();
error_log(print_r($prix,true), 3, "/var/tmp/error.log");
return json_encode($prix);
}
I tested the PHP code and it works fine. The problem is when I tried to populate the selectbox, I think in the success method. Help me please! Thanks in advance!
Upvotes: 0
Views: 818
Reputation: 2582
<input type="text" id="{{ form_gift.prix.name }}" name="{{ form_gift.prix.name }}" value="" placeholder="" class="form-control txtPrix" required="required"/>
success: function (result) {
$('.txtPrix').val(result.id);
}
Upvotes: 1
Reputation: 337560
Given the format of the returned JSON:
the format of json is like this: {"id":"59.90"}
You need to access that value using the id
key, try this:
success: function (result) {
$('#prix').val(result.id);
}
Upvotes: 1