我有以下代码。但似乎变量 v 始终为空。所以 select2 无法获取 json 响应。我的方法获取另一个元素的值有什么问题?
<script>
$(document).ready(function() {
var v = $('select#box_name').find('option:selected').val();
$('#box_assoc_items').select2({
placeholder: 'choose items',
multiple: true,
ajax: {
url: "/dishes/"+v+"/get_assoc_items.json",
dataType: 'json',
data: function(term, page) {
return { q: term, page: page, per: 10
}
},
results: function(data, page) {
return { results: data }
}
}
});
});
</script>
<%= simple_form_for([@restaurant, @order, @box]) do |f| %>
<%= f.input :name, :collection => @dishes %>
<%= f.input :assoc_items, :input_html => {:type => "hidden", :maxlength => 2, :style => 'width:400px'} %>
<%= bootstrap_button(f, "Add a dish") %>
<% end %>
等效的html如下:
<form accept-charset="UTF-8" action="/restaurants/5/orders/4/boxes" class="simple_form new_box" id="new_box" method="post"><div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="zd3shkqtmbfFe3Sl3aoG39gQj1mslX7FHPHGJsgqxzQ=" /></div>
<div class="input select optional box_name">
<label class="select optional" for="box_name">Name</label>
<select class="select optional" id="box_name" name="box[name]">
<option value=""></option>
<option value="9">combo 3</option>
<option value="10">test dish</option>
<option value="11">test 20</option></select></div>
<div class="input string optional box_assoc_items">
<label class="string optional" for="box_assoc_items">Assoc items</label>
<input class="string optional" id="box_assoc_items" maxlength="2" name="box[assoc_items]" size="50" style="width:400px" type="hidden" /></div>
<div class="control-group">
<div class="controls">
<input class="button btn btn-primary" name="commit" type="submit" value="Create Box" />
</div>
</div>
</form>