简体   繁体   中英

Populate a textbox based on selectbox ajax php mysql

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM