简体   繁体   中英

How to set option value according to my ajax request?

I have an html having select options there. by default there is default value is selected like first option. somewhere I request ajax request to get value for that select options. I got it 3(eg) I do something using Jquery but value is not getting updated. here is my snippet.

HTML code

<select class="form-control custom-form-control font-16 table-form-control" id="edit_merchant_id">
    <option value="">Select Merchant</option>
        <option value="1" merchantname="Yoox.com">Yoox.com</option>
        <option value="2" merchantname="Best Buy">Best Buy</option>
        <option value="3" merchantname="Walmart">Walmart</option>
        <option value="4" merchantname="Lane Bryant">Lane Bryant</option>
        <option value="5" merchantname="Reebok">Reebok</option>
        <option value="6" merchantname="adidas">adidas</option>
        <option value="7" merchantname="Urban Outfitters">Urban Outfitters</option>
</select>

Jquery code

$("#edit_merchant_id select").val(parseInt(response.merchant_id));

Your selector is not correct $("#edit_merchant_id select") replace with $("#edit_merchant_id")

 var response = {}; response.merchant_id = 5; $("#edit_merchant_id").val(response.merchant_id); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control custom-form-control font-16 table-form-control" id="edit_merchant_id"> <option value="">Select Merchant</option> <option value="1" merchantname="Yoox.com">Yoox.com</option> <option value="2" merchantname="Best Buy">Best Buy</option> <option value="3" merchantname="Walmart">Walmart</option> <option value="4" merchantname="Lane Bryant">Lane Bryant</option> <option value="5" merchantname="Reebok">Reebok</option> <option value="6" merchantname="adidas">adidas</option> <option value="7" merchantname="Urban Outfitters">Urban Outfitters</option> </select> 

You can do like this

This will select the select the select & option & will update selected option

$('#edit_merchant_id option[value="3"]').attr('selected', 'selected')

DEMO

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