我有一个ajax脚本,它选择必要的数据并返回数组
服务器响应
[{"id":67,"title":"first","selected":"first"},
{"id":68,"title":"second","selected":"first"},
{"id":69,"title":"third","selected":"first"},
{"id":70,"title":"fourth","selected":"first"}]
脚本
$(document).ready ->
category_id = $('#product_category_id').attr('selected', 'selected').val()
product_id = $('#product_id').val()
$.ajax
type: 'GET'
url: "/products/dynamic_admin_subcategory?category_id=#{category_id}&id=#{product_id}"
dataType: 'json'
success: (data) ->
$('#product_subcategory_id').empty()
subcat = $('#product_subcategory_id')
$.each data, (value, key) ->
console.log(key)
$("<option />", {value: key.id, text: key.title}).appendTo(subcat);
$("#product_subcategory_id option:selected").val(key.id).text(key.selected)
return
return
它工作正常,但我无法设置选定的
我也试过
$("#product_subcategory_id option[value=key.selected]").prop("selected", "selected")
但无法将值传递给option[value=key.selected]
我该怎么办?
答案 0 :(得分:0)
我修好了
改变
$("#product_subcategory_id option:selected").val(key.id).text(key.selected)
到
$("#product_subcategory_id option[value=#{key.selected}]").prop("selected", "selected")
key.selected
==选择的子类别ID