I want add some items to a selectized input after user clicks on a button. The input data are loaded via Ajax. When I call addItem(value) no thing happens. But if I try to type some string in the input it loads data and after this addItem(value) will works.
https://github.com/brianreavis/selectize.js/blob/master/docs/api.md
This plugin does not attempt to load an item metadata from the server. You need to first add an option using addOption() method. Next, you can use addItem().
v.selectize.addOption({value:13,text:'foo'}); //option can be created manually or loaded using Ajax
v.selectize.addItem(13);
You can add options like this:
var $select = $(document.getElementById('mySelect')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value: 1, text: 'whatever'});
selectize.refreshOptions();
This only adds the option as possible selection. Now you can use addItem to add the new option to the list:
selectize.addItem(1);
This does not need a refresh function. You do not need to use "refreshOptions" if you add the new option immediately.
Try this.
$('.select-ajax-city').each(function() {
if (this.selectize) {
for(x=0; x < 10; ++x){
this.selectize.addOption({value:x, text: x});
}
}
});
Try This
var $select = $(document.getElementById('Your-element-id'));
var selectize = $select[0].selectize;
selectize.addOption({value: '2', text: 'test'});
selectize.addItem('2');
If you want to be more flexible then you can use the length like this.
var $select = $(document.getElementById('Your-ID'));
var selectize = $select[0].selectize;
var count = selectize.items.length + 1;
selectize.addOption({ value: count, text: 'value-here' });
selectize.addItem(count);
$('#id').selectize({
create: function(input,callback){
$.ajax({
url: "",
type: "POST",
data: {value : input},
success: function(res) {
callback({value: res, text: input});
}
});
}
});
For adding new options dynamically is neccesary to call clearOptions for clean the options, adding the new list options using addOption and call refreshState function after all.
var listItems = [{id: 1, value: 'Element1'},{id: 2, value: 'Element2'}]
/* Initialize select*/
var $select = $('#element').selectize();
var control = $select[0].selectize;
control.clear()
control.clearOptions();
/* Fill options and item list*/
var optionsList = [];
var itemsList = [];
$.each(listItems, function() {
optionsList.push( {
value: this.id,
text: this.value
});
itemsList.push({
value: this.id,
text: this.value
});
});
/* Add options and item and then refresh state*/
control.addOption(optionsList)
control.addItems(itemsList);
control.refreshState();
/* Add element 1 selected*/
$.each(result, function() {
if (this.id == 1) {
control.addItem(this.Tax.id,this.Tax.title);
}
});
This is another way you can add items manually if you have set other values to your select:
$('select').selectize({
create: true,
sortField: "text",
hideSelected: false,
closeAfterSelect: false,
options:[
{
text:'<text goes here>',
value:'<value goes here>',
}
]
});
Related
I have a data, when I update the data (using modal), select option work correctly
When I close the modal, and I click the edit button again, something wrong with select option:
This is my edit modal ajax:
// Function for edit modal plan schedule
$('body').on('click', '.editPlanSchedule', function() {
var Item_id = $(this).data('id');
$.get("/quotation/getEditPlanSchedule" + '/' + Item_id, function(data) {
console.log(data['product_plan']);
$('.modal-title-edit').html("Edit Plan Schedule Item");
$('#saveBtn').val("Update");
$('#updatePlanSchedule').modal('show');
$('#id').val(data['data'].id);
$('#qno').val(data['data'].qno);
$('#b_amount').val(data['data'].b_amount);
// $('#product_plan_edit').val(data.product_plan);
data['product_plan'].forEach(function(item, index) {
$('#product_plan_edit').append($('<option>', {
id: item.id,
value: item.productplanID,
text: item.productplanID
}));
if(data['data'].product_plan == item.productplanID){
$('#'+item.id).attr('selected',true);
}
});
})
});
This is the method from controller:
public function getEditPlanSchedule($id)
{
$item['data'] = QuotationPlanSchedule::find($id);
$item['product_plan'] = ProductPlan::orderby('id', 'asc')->get();
return response()->json($item);
}
You have to clear all options before adding again:
$("#product_plan_edit").empty();
Either .empty the container or don't use append (better for the DOM update)
I am a little confused about your use of data['data'].product_plan to test the ID. In any case you can see the principle
$('#product_plan_edit').html(
data['product_plan'].map(item => `<option value="${item.productplanID}">${item.productplanID}</option>`).join('')
);
$('#product_plan_edit').val(data['data'].product_plan); // select item.productplanID === data['data'].product_plan
The example I would like to replicate is this: https://jsfiddle.net/bindrid/hpkqxto6/ . I need to load data from the server, form a grouping of them and when selecting one item from one group all other items inside this particular group would become disabled. The difference is that I must load data from the server using an ajax call inside select2, instead of listing the < option > elements inside the select element and form a grouping this way. I have trouble selecting all available items in the dropdown list during the javascript manipulation in order to disable items from the same group (line 29 in the above example fails due to there being no < option > elements in html, instead I think they are loaded later and javascript is not able to find them).
The html part looks as follows:
<select class="form-control attributoSelect2" name="attributiSelezionati" id="attributoSelect2" value="#Model.AttributiSelezionati"></select>
There are no < option > items inside < select > because the ajax call takes care of populating the list, like this:
$('.attributoSelect2').select2({
placeholder: "Cerca Attributo",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.CercaAttributi())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Descrizione,
children: item.Children.map(function (itemC) {
return {
id: itemC.Id,
groupid: itemC.GroupId,
text: itemC.Descrizione,
};
})
};
})
};
}
}
});
Finally my javascript looks as follows:
$('.attributoSelect2').on("select2:selecting", function (evt, f, g) {
disableSel2Group(evt, this, true);
});
$('.attributoSelect2').on("select2:unselecting", function (evt) {
disableSel2Group(evt, this, false);
});
function disableSel2Group(evt, target, disabled) {
var selId = evt.params.args.data.id;
var group = evt.params.args.data.groupid;
var aaList = $(".attributoSelect2 option");
$.each(aaList, function (idx, item) {
var data = $(item).data("data");
var itemGroupId = data.groupid;
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The problem is that this line:
var aaList = $(".attributoSelect2 option");
does not load all the option elements because they are not loaded yet. They would be loaded later on using the ajax call. Does anyone have an idea of how to resolve this problem?
I want to utilize the Kendo UI Context Menu in my app. I was expecting the standard behavior of having text displayed in the menu itself but a different value (an ID or key) being returned to the select event handler.
For instance, the menu displays a list of names but when I click on one of them, I get the ID associated with the name.
I've tried adding additional properties besides text to the array of items in the context menu but I don't see them on the event object in the handler.
I can't use the text to find the appropriate id that matches it since there could be entries with the same text but different IDs.
Any ideas?
Edit:
Currently I build the context menu like this:
open: (e) => {
let itemKeys = [1, 2, 3];
let menu = e.sender;
menu.remove(".context-menu-item");
menu.append(itemKeys.map((itemKey) => {
return {
text: "<div data-item-key='" + itemKey + "'>Test Text</div>",
cssClass: "context-menu-item",
encoded: false
};
}));
}
While this solution does satisfy my needs, it adds an extra element to the DOM which, while being insignificant, isn't perfect...
It's undocumented, but ContextMenu actually inherits from Menu. Therefore, all options of Menu are available. In particular, you can add an attr object to your data items, cf the example in the documentation.
To complete your example:
open: (e) => {
let itemKeys = [1, 2, 3];
let menu = e.sender;
menu.remove(".context-menu-item");
menu.append(itemKeys.map((itemKey) => {
return {
text: "Test Text",
cssClass: "context-menu-item",
// add whatever attribute
attr: {
'data-item-key': itemKey
}
};
}));
}
Then, in your select handler:
select: (e) => {
console.log($(e.item).data('item-key'));
}
Option 1)
You might add a data that will specify your Id.
I made this with mvc wrapper but it can be done with pure javascript as well.
#(Html.Kendo()
.ContextMenu()
.Name("contextMenuGridTicketTestiMessaggi")
.Target("#gridTicketTestiMessaggi")
.Filter("tr")
.Orientation(ContextMenuOrientation.Vertical)
.Items(items =>
{
items.Add().Text("Update").HtmlAttributes(new { data_toggle = "update" });
items.Add().Text("Save").HtmlAttributes(new { data_toggle = "save" });
items.Add().Text("Delete").HtmlAttributes(new { data_toggle = "delete" });
})
.Events(e => {
e.Select("contextMenuGridTicketTestiMessaggiSelect");
}));
var contextMenuGridTicketTestiMessaggiSelect = function(e) {
var action = $(e.item).data("toggle");
var that = this;
if (action === "update") {}
...
Option 2) You might define with every item(throught html content) a function to be called in each onClick event for the specific item.
items.Add().Encoded(false).Text("<span onclick='update()'>Update</span>");
items.Add().Encoded(false).Text("<span onclick='delete()'>Delete</span>");
...
Update
<div id="target">Target</div>
<ul id="context-menu"></div>
<script>
$("#context-menu").kendoContextMenu({
target: "#target",
open: function(e) {
let itemKeys = [1, 2, 3];
let menu = e.sender;
menu.remove(".context-menu-item");
menu.setOptions({
dataSource: itemKeys.map((itemKey) => {
return {
text: "<div data-item-key='" + itemKey + "' style='white-space: nowrap'>Test Text</div>",
cssClass: "context-menu-item",
encoded: false
};
})
});
},
select: function(e) {
console.log($($(e.item).find("div")[0]).data("item-key"))
}
});
</script>
I was looking in several threads about retrieving values from a drop down box to use the values for a later time in the casperjs script.
So my issue is that I can't fetch the values from my drop down box and actually use it in my next step, for now just to echo it out.
This is how my drop down box looks in my web page:
I did tried some examples but it just doesn't work, what am I doing wrong?
casper.then(function() {
var options = this.evaluate(function() {
var options = document.getElementById('selectedNetworkElementOrGroup_TD').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));
});
One problem could be that the drop down box has no id!
You need a basic CSS selector like this one: #selectedNetworkElementOrGroup_TR select:
var options = this.evaluate(function() {
var options = document.querySelector('#selectedNetworkElementOrGroup_TR select').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));
So I am using the multiselect widget from here: http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/ and it is working fine in this instance. When I use strictly the same dropdown styling (to appear consistent) with a normal (only choose 1 option) dropdown my problem is that the drop down says 1 Selected. I need to change this to show the selected option, so 'Red' from Red, Yellow, Blue. The code that determines the selected option text is as follows:
$.widget("ech.multiselect", {
// default options
options: {
header: true,
height: 175,
minWidth: 225,
classes: '',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select options',
selectedText: '# selected',
selectedList: 0,
show: null,
hide: null,
autoOpen: false,
multiple: true,
position: {},
appendTo: "body"
}
So, I need the selectedText to show the selected option if the dropdown has the class .normal. Any ideas? Thanks in advance.
You have to change some code in the jquery.multiselect.js file.
Replace the update function with this code:
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else if( numChecked===1){
value = $checked.val();
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
I haven't tested this but tell if it works for you.
I have the same problem and im using javascript 1.7.2
The problem is the selectedText only taken into account for the first time loading and when i change the checkbox, slectedText of my button is not changing. Finally, i manage to fix the problem by modifying the jquery.multiselect.js like this :
In _create: function ()
Edit buttonlabel to:
buttonlabel = (this.buttonlabel = $(''))
.html(o.noneSelectedText)
.appendTo(button)
.attr("id", "buttonlabel_" + this.element.attr('id')),
In update: function ()
Change this.buttonlabel.html( value ) to $("#buttonlabel_" + this.element.attr("id")).text(value);
Hope this helps.
Cheers