我正在使用Chosen Jquery插件。提交表单失败后,我需要保留选定的值。我有这么多值的单选。我这样结束了:
var app = angular.module('app', [ 'oc.lazyLoad', 'ui.router',
'ncy-angular-breadcrumb' ]);
app.config([ '$ocLazyLoadProvider', function($llp) {
$llp.config({
debug : true
});
} ]);
app.config([ '$stateProvider', '$locationProvider',
function($sp, $locationProvider) {
for (var i = 0; i < config.length; i++) {
var obj = config[i];
$sp.state(obj.state, {
url : obj.url,
templateUrl : obj.html,
ncyBreadcrumb : {
label : obj.label,
parent : obj.parents
},
resolve : {
load : loadDeps(obj.js)
},
data : {
pageTitle : obj.pageTitle
}
});
}
$sp.state('otherwise', {
url : '*path',
controller : function($state) {
$state.go("terminal");
}
});
function loadDeps(deps) {
return [ '$ocLazyLoad', function($ll) {
return $ll.load(deps);
} ];
}
} ]);
并使用javascript通过 script.js 文件显示选项值:
<select name="fruits" id="fruits" data-placeholder="Choose a fruit...">
<optgroup label="Green color fruit" id="opt-group-1"></optgroup>
<optgroup label="Yellow color fruit" id="opt-group-2"></optgroup>
// keep going until 20 optgroup ....
</select>
实际上我使用的是codeigniter,并且有很多示例代码可以在提交表单失败后使用手动代码保留选定的值,如下所示:
<script>
var group1 = ['melon', 'watermelon', 'kiwi', ...];
var group2 = ['banana', 'pinapple', 'lemon', ...];
// ....
var option1 = '';
for (var i=0;i<group1.length;i++){
option1 += '<option value="'+ group1[i] + '">' + group1[i] + '</option>';
}
var option2 = '';
for (var i=0;i<group2.length;i++){
option2 += '<option value="'+ group2[i] + '">' + group2[i] + '</option>';
}
// ....
$('#opt-group-1').append(option1);
$('#opt-group-2').append(option2);
// ....
</script>
有没有“jquery方式”来做到这一点?
答案 0 :(得分:0)
我认为这可以毫无困难地运作 使你的观点适应
<select name="fruits" id="fruits" data-placeholder="Choose a fruit..." data-current-selected-option="<?=$this->input->post("fruits"); ?>">
<optgroup label="Green color fruit" id="opt-group-1"></optgroup>
<optgroup label="Yellow color fruit" id="opt-group-2"></optgroup>
// keep going until 20 optgroup ....
</select>
和你的脚本js
var currentSelectedPostValue = $("#fruits").attr("data-current-selected-option");
function setOptionGroupValues(arrGroup, strTargetGroup)
{
var option = '';
for (var i=0;i<arrGroup.length;i++)
{
var strSelected = (currentSelectedPostValue == arrGroup[i]) ? " selected=\"selected\"" : "";
option += '<option value="'+ arrGroup[i] + '"'+strSelected+'>' + arrGroup[i] + '</option>';
}
$(strTargetGroup).append(option);
}
var group1 = ['melon', 'watermelon', 'kiwi',...];
setOptionGroupValues(group1);