简体   繁体   中英

Manipulate select option from existing value on a record in database using jquery

I have a form to edit a record from a database. So, to pull all the data from this record, I use ajax jquery and I displayed into a modal's bootsrap. The code looked like this :

<div class="control-group">
<label class="control-label">Perusahaan : </label>
<div class="controls">

    <select id="perusahaan_edit" name="perusahaan-edit">
        <option>Tresnamuda Sejati</option>
        <option>Jameson-Freight Semesta </option>
        <option>Samudera Daka Line </option>
        <option>Meridian Port Anances </option>
        <option>StarLine</option>
    </select>

</div>

See, let say on database, the value that exist is StarLine , how can I make it selected :

My jquery code

$(document).on('click', '#btn-edit-dataPC', function() {
var $this = $(this);
var nama = $this.attr("req_id");

$.ajax({
    url: "<?php echo base_url() . 'administrator/control_admin/get_one_pc' ?>",
    type: 'POST',
    data: {nama: nama},
    dataType: 'json',
    success: function(obj) {
        // manipulate the select option ???

        //Show on modal
        $('#myModal1').modal('show');
        }
    });
});

Any help it so appreciated...

Update

Thanks for the reply, I got some problem here. Is it a problem if the return ajax is a json ? Coz, if I use like this :

success: function(obj) {

                var value = obj.perusahaan;

                $("#perusahaan_edit option").filter(function() {
                    return $(this).text() === value;
                }).attr("selected", "selected");


                $('#myModal1').modal('show');
            }

which var value is dynamic on database ? I got the select option is not affected. Thanks again ...

You can change the <option> elements selected attribute with jquery when your ajax call completes.

Try this:

$("select option:contains(StarLine)").attr('selected', true);

Or

$("select option").filter(function() {
    return $(this).text() === "StarLine";
}).attr("selected", "selected");

fiddle

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