我通过AJAX生成选项。这些选项可以选择anohter select。
第一个包含追加数据的函数:
var appendto_c = function(appendto, value, curcode) {
appendto.append("<option value=\"" + value.currency_value + "\">" + value.type + " " + curcode + value.currency_value + "</option>"); //set the option
$(".currency_val").find(".select2-chosen").html(value.type + " " + curcode + value.currency_value); //set the placeholder
}
第二个函数执行ajax并附加到select中,具体取决于它将从主下拉列表中获得的货币ID:
var showcurval = function(cur_code) {
var $options = $('.currency_v'); // the optgroup append to
var $curcode = '';
$.ajax({
type: 'GET',
url: '/transactions/get_currency_val?cur_code=' + cur_code,
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function (k, v) {
switch (v.currency_code) {
case '47':
$curcode = '€';
appendto_c($options, v, $curcode);
break;
case '33':
$curcode = 'Kč';
appendto_c($options, v, $curcode);
break;
case '131':
$curcode = '₽';
appendto_c($options, v, $curcode);
break;
case '144':
$curcode = '$';
appendto_c($options, v, $curcode);
break;
case '168':
alert('Please set a currency!');
break;
}
});
}
});
}
最终功能是将货币代码发送给showcurval ..
var selectcurrency = function() {
var $currency = $(".currency_input").select2(); // main input
var $curval = $('.currency_val').select2(); // secondary select with our values
var $options = $('.currency_v'); // the optgroup append to
$currency.on('change', function(e) {
showcurval($(this).select2('data').id);
});
}
selectcurrency();
JSON:
[{"currency_value":"26.98","currency_code":"47","type":"BUY"},{"currency_value":"25.98","currency_code":"47","type":"SELL"}]
现在每次更改selectcurrency();
附加选项后,选择其他货币保留旧货币。我试图使用html而不是追加,但在选择中只出现1个选项..建议?
答案 0 :(得分:0)
您应该在附加值之前清空$选项。
var showcurval = function(cur_code) {
var $options = $('.currency_v'); // the optgroup append to
var $curcode = '';
$.ajax({
type: 'GET',
url: '/transactions/get_currency_val?cur_code=' + cur_code,
success: function(data) {
var obj = JSON.parse(data);
$options.html("");
$.each(obj, function (k, v) {
switch (v.currency_code) {
case '47':
$curcode = '€';
appendto_c($options, v, $curcode);
break;
case '33':
$curcode = 'Kč';
appendto_c($options, v, $curcode);
break;
case '131':
$curcode = '₽';
appendto_c($options, v, $curcode);
break;
case '144':
$curcode = '$';
appendto_c($options, v, $curcode);
break;
case '168':
alert('Please set a currency!');
break;
}
});
}
});
}
答案 1 :(得分:0)