[英]How can I change hidden input val when add or remove item with using select2 plugin
I use select2 plugin and get values when user typing least 3 character. 我使用select2插件,并在用户键入至少3个字符时获取值。 Get data from php as json like this;
像这样以json格式从php获取数据;
"1":"val1" , "5":"val2" , "19":"val3"....
I want to store id values of selected items at hidden input and when user remove any selected item, the id of removed item also remove from hidden input. 我想在隐藏输入中存储选定项的ID值,并且当用户删除任何选定项时,被删除项的ID也会从隐藏输入中删除。 For example;
例如;
When val1 and val2 items are selected like below, value of hidden input (id which 'hdn-id') change like below, also. 当像下面一样选择val1和val2项目时,隐藏输入的值(“ hdn-id”的id)也会像下面那样变化。
<input type="hidden" id="hdn-id" val="1,5" />
And when val1 is removed, id of this item (1) removed from hidden input like this ; 并且当val1删除时,此项的ID(1)的ID从这样的隐藏输入中删除;
<input type="hidden" id="hdn-id" val="5" />
But I can't do this. 但是我做不到。 My codes;
我的密码;
SELECT2: 选择2:
function selectAjax(element,url,hiddenElement) {
var selectedItemsArray = []
$('#'+element).select2({
multiple: multi,
id: function(element) {
return element
},
ajax: {
url: url,
dataType: 'json',
data: function(term,page) {
return {
term: term,
page_limit: 10
};
},
results: function(data,page) {
var titleArr = [];
$.each(data, function(k,v){
titleArr.push(k+':'+v);
});
return {
results: titleArr
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
});
function formatResult(data) {
return '<div>'+data.substr(data.indexOf(':')+1)+'</div>'
};
function formatSelection(data) {
var id = data.split(':',1),
text = data.substr(data.indexOf(':')+1),
hiddenElementValue = eval([jQuery('#'+hiddenElement).val()]);
selectedItemsArray.push(id);
jQuery('#'+hiddenElement).val(selectedItemsArray);
return '<div data-id="'+id+'" class="y-select2-selected-items">'+text+'</div>';
};
}
selectAjax('select2-element','ajx.php','hdn-id');
HTML: HTML:
<input type="text" id="select2-element" />
<input type="hidden" id="hdn-id" />
I can store ids at hidden input with above code but when remove an item I can't remove id from hidden input. 我可以使用上面的代码将ID存储在隐藏的输入中,但是当删除项目时,我无法从隐藏的输入中删除ID。 Because plugin assign 'return false' to element's onclick event.
因为插件将'return false'分配给元素的onclick事件。 I handed the job with above codes, I think.How can I be a better solution?
我认为我是用上述代码来完成这项工作的。如何才能成为更好的解决方案?
You can use the change
event of the select2 plugin and there write some code that will update the value of the hidden input. 您可以使用select2插件的
change
事件,然后编写一些代码来更新隐藏输入的值。
$("#select2-item").select2({
//options go here
});
$("#select2-item").on("change", function(e) {
//update hidden input value
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.