下面是我的代码用于使用tokeninput在文本中添加选项数量。在保存按钮后选择标签我将选择为数组并将其保存在数据库中,如美国,爱尔兰在国家/地区列中。保存后想要预填充保存使用jquery方法将数据作为标记.Below是此过程的参考代码。
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"/>
<link rel="stylesheet" href="styles/token-input.css" type="text/css" />
<script type="text/javascript" src="src/jquery.tokeninput.js"></script>
<script>
var country_list=[
{id: 1, name: "UK"},
{id: 2, name: "CANADA"},
{id: 3, name: "IRELAND"},
{id: 4, name: "SINGAPORE"},
{id: 5, name: "AUSTRALIA"},
{id: 6, name: "NEWZEALAND"},
{id: 7, name: "SWITZERLAND"},
{id: 8, name: "CYPRUS"},
{id: 9, name: "FRANCE"},
{id: 10, name: "MALAYSIA"},
{id: 11, name: "ITALY"},
{id: 12, name: "SWEDEN"},
{id: 13, name: "GERMANY"},
{id: 14, name: "USA"},
{id: 15, name: "DUBAI"},
{id: 16, name: "SPAIN"},
{id: 17, name: "LITHUANIA"},
{id: 18, name: "NETHERLANDS"},
{id: 19, name: "LATVIA"},
{id: 20, name: "SOUTH AFRICA"},
{id: 21, name: "OTHERS"}
];
var selected_countries=<?php echo json_encode(explode(",",$country));?>;
//alert(selected_countries);
var populate_list=[];
var index;
for (index = 0; index < country_list.length; ++index) {
console.log(country_list[index]);
if(selected_countries.indexOf(country_list[index].name)>-1){
populate_list.push(country_list[index]);
}
}
var prepopulate = {
prePopulate : populate_list
};
$("#country").tokenInput(country_list,prepopulate);
</script>
HTML代码
<input type="text" name="country" id="country">
为了保存结果我使用的数据库中的所有选定文本
AJAX代码
var arr1 = $('#country').tokenInput("get");
var names1 = [];
$.each(arr1, function(i, obj)
{
names1.push(obj.name);
});
var country=names1.join();
结果数据库端和UI端
答案 0 :(得分:1)
来自http://loopj.com/jquery-tokeninput/
预填充 使用现有数据预填充tokeninput。设置为 JSON对象数组,例如:[{id:3,name:&#34; test&#34;},{id:5,name: &#34; awesome&#34;}]预填充输入。
var country_list=[
{id: 1, name: "UK"},
{id: 2, name: "CANADA"},
{id: 3, name: "IRELAND"},
{id: 4, name: "SINGAPORE"},
{id: 5, name: "AUSTRALIA"},
{id: 6, name: "NEWZEALAND"},
{id: 7, name: "SWITZERLAND"},
{id: 8, name: "CYPRUS"},
{id: 9, name: "FRANCE"},
{id: 10, name: "MALAYSIA"},
{id: 11, name: "ITALY"},
{id: 12, name: "SWEDEN"},
{id: 13, name: "GERMANY"},
{id: 14, name: "USA"},
{id: 15, name: "DUBAI"},
{id: 16, name: "SPAIN"},
{id: 17, name: "LITHUANIA"},
{id: 18, name: "NETHERLANDS"},
{id: 19, name: "LATVIA"},
{id: 20, name: "SOUTH AFRICA"},
{id: 21, name: "OTHERS"}
];
var selected_countries=<?php echo json_encode(explode($country));?>;
var populate_list=[];
var index;
for (index = 0; index < country_list.length; ++index) {
if(selected_countries.indexOf(country_list[index].name)>-1){
populate_list.push(country_list[index]);
}
}
var prepopulate = {
prepopulate : populate_list
};
$("#country").tokenInput(country_list,prepopulate);
答案 1 :(得分:1)
将输入文本框更改为以下内容:
<input type="text" name="country" id="country" value='<?php echo $country; ?>' data-country='<?php echo $country; ?>'>
然后添加prePopulate参数,如下所示:
prePopulate: $('#country').data('country')