I am attempting to have Select2 (4.0.0rc1) multi-value select box have preloaded data, but it is not working.
HTML
<select id="sj" class="js-example-basic-multiple form-control" multiple="multiple">
<option value="1">Tickets</option>
<option value="2">PArking</option>
<option value="3">Special Events</option>
<option value="4">Athletics</option>
</select>
JavaScript
$(document).ready(function() {
$("#sj").select2();
$("#example tbody").on("click", "tr",function(){
var defaultData = [{id:1, text:'Tickets'},{id:2,text:'Parking'},{id:3,text:'Athletics'}];
$("#sj").select2({data:defaultData});
});
I want this code to programmatically prepopulate the selected items on click.
EDIT
what I'm after: The drop down has a total of N Multi- selectable items , i click on a row , and it passes in 3 options as initially selected, how do i do an initSelection as 3.5.2 did? Think of it this way: I am using the multi select drop down to show attributes associated, if its a sporting event, It may only come with tickets, but a week from now i may want to add parking for this event, but it needs to remember I already had tickets associated with this event
I accomplished this in 3.5.2 doing the following:
initSelection : function (element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.cfm/tickets/select2get", {
dataType: 'json',
data: {
nd_event_id: $('#nd_event_id').val(),
passes: 'TK,PK,ATH',
},
}).done(function(data) { callback(data); });
}
},
But this will not work in 4.0.0 due to migration from inputs to selects
Easier to understand if we separate the logic/code into smaller chunks and then tie them together... easier to debug as well if things go wrong. So you'll need:
Drop-down items to populate in the format of (key, value) which the
Select2 format is (id, text). You've got that correct, so let's
put that into a variable:
var infoCategory = [
{
"id": 1,
"text": "Tickets"
},
{
"id": 2,
"text": "Parking"
},
{
"id": 3,
"text": "Special Events"
},
{
"id": 4,
"text": "Athletics"
}
];
Select2 needs to know about the dropdown items we just created and it will be looking for a configuration of data as well as other options. Basically, "data" is one of the configuration options you pass along to it, if the <select> element doesn't have any <option> child elements. So let's create another variable for the Select2 configuration options as such:
var select2Options = {
"multiple" = false,
"data" = infoCategory
};
A full list of the default Select2 options can be found in their documentation.
Create the <select> element:
<select id="name="s2select01"></select>
Now, either you can directly initialize Select2 with configuration options (which includes drop-down data), like you did in your example, as such:
$('#s2select01').select2(select2Options);
Or you can use the above initialization line of script in a click event and tie it to another element, like so:
$('#someButtonID').click(function () {
$('#s2select01').select2(select2Options);
});
I've created a verbose demonstration on CodePen so you can see it all tied together.
Related
I'm facing a problem in using UI-GRId with row selection and custom cell elements:
The sample plunker is here : http://plnkr.co/edit/Ed6s6CGFGXyUzj2cyx2g?p=preview
$scope.gridOptions = { showGridFooter:true,enableRowSelection: true, enableRowHeaderSelection: false };
$scope.gridOptions.columnDefs = [
{ name: 'id' },
{ name: 'name'},
{ name: 'age', displayName: 'Age (not focusable)', allowCellFocus : false },
{ name: 'address.city' },
{ name:'address.pin',cellTemplate:'<select><option value="122002">122002</option><option value="122001">122001</option></select>'}];
You can see that on row click, the respective row gets selected, while if you tend to select the dropdown options implicitly the row selection event also gets fired, I want that on elements click like dropdown here the row selection event should not be triggered.
Pls guide.
Interesting question, haven't run into it yet, but I am sure it's only time before I do. I've created a plunk to demonstrate my solution.
Basically, what I have do is registered a watcher, as mentioned by AranS. From there, we have two objects to work with: the row, and the event that occured. Since the event object discloses which element was selected (clicked), we can identify if it was a DIV, or something else. In the event of the change in the select list, the value of evt.srcElement.tagName is 'SELECT'.
http://plnkr.co/edit/k2XhHr2QaD1sA5y2hcFd?p=preview
$scope.gridOptions.onRegisterApi = function( gridApi ) {
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row,evt){
if (evt)
row.isSelected = (evt.srcElement.tagName === 'DIV');
});
};
ui-grid's API allows controlling row selection. Look at this answer from another thread: https://stackoverflow.com/a/33788459/5954939. Basically you can use the event rowSelectionChanged or the isRowSelectable. Let me know if you need an example.
I'm using select2 with multiple options and programmatic access to select also with a button. It works fine but when I click on the button all previously selected values are removed and only the value from the clicked button gets selected. Since I'm using multiple select it would make sense to add the clicked value and leave the previously selected without removing them... Is there another event to trigger besides "change" that does not remove values but adds them instead?
<select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
</select>
<td><button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" name="{{teu.entity}}"><i class="fa fa-plus"></i></button></td>
<td>{{teu.entity}}</td>
<td>{{teu.user}}</td>
<script >
$(".js-example-programmatic").select2({
minimumInputLength: 2,
placeholder: "Select entities...",
allowClear: true,
multiple:true,
delay: 250,
tags:false,
ajax: {
url: '/entities/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { title: parms.term }; },
},
});
</script>
<script>
var $example = $('#id_entities');
$("button[id^='prefix_']").click(function(){
value = $(this).attr('value');
value_name = $(this).attr('name')
if ($('#id_entities option[value="'+value+'"]').length > 0) {
}
else {
$("#id_entities").append('<option value="'+value+'">'+value_name+'</option>');
}
$example.val(value).trigger("change");
});
</script>
well, without seeing a working demo, I assume what you want is to append tags on to a select2 without erasing what tags/multi-selects are already there? If so, you would need to evaluate the element value, and append new vals rather than just calling $example.val(value), which replaces the value of said element
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Seels like a duplicate of SELECT2 -> Add data without replacing content
i am try to create a array of selected id using kendo multi select.
here is jsfiddle
this is kendo script:-
$("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
select:onSelect
});
kendo select function:-
function onSelect(e){
var dataItem = this.dataSource.view()[e.item.index()];
onchng(dataItem.id);
}
create a array:-
function onchng(id){
var checkarr = [];
checkarr.push(id);
console.log(checkarr);
}
here is output is [1] [2]
but i want it ['1','2']
is it possible??
thanks
When your select event fired, 'checkarr' redefined again and again. Your problem is that. If you want values in one array, you must use a button to take values together, then push them to array in single function. Or you can use session or something like that
This is how you can do it from the Controller. Note I'm doing Request.Form, that's because for whatever reason MVC Model and Kendo UI wouldn't work together when using MultiComplete. But this will put them in an array, and this is fired off a button click like the other answer suggested.
string[] advertisers = Request.Form["Name"].ToString().Split(',');
I think that there is a much easier approach and with less side effects...
Bind change event instead of select. Why? Two reasons:
select is fired just before the element is added to the list of values so you cannot get current list and you need to add the value being selected to the values already selected.
select is not fired when you remove the selection of an option.
The code using change would be as simple as:
var multi = $("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
change : onSelect
}).data("kendoMultiSelect");
function onSelect(){
console.log("here", multi.value());
}
Just need to use value method from your multiselect.
Your Fiddle modified in here : http://docs.telerik.com/kendo-ui/api/framework/datasource#events-change
NOTE: change event belongs to DataSource if you need to see the documentation, check it here
I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});
I have two drop down lists:
<select name="branch">
<option value="b">Blacksburg</option>
<option value="c">Christiansburg</option>
<option value="f">Floyd</option>
<option value="m">Meadowbrook</option>
</select>
but I would like the second list to be different based upon what is selected from the first list. So FREX Blacksburg's might be:
<select name="room">
<option value="Kitchen">Kitchen Side</option>
<option value="Closet">Closet Side</option>
<option value="Full">Full Room</option>
</select
While Christiansburg's is:
<select name="room">
<option value="Window">Window Side</option>
<option value="Door">Door Side</option>
<option value="Full">Full Room</option>
and of course the options are also different for the other branches...
Is it possible to change the second drop down list based on what they select for the first one? I have used JavaScript a teensy bit, but not much so please explain in detail.
Yes, this is called a drilldown.
What you want to do is attach an onChange handler to your first dropdown that will grab new values based on the selected value (of the first dropdown) and populate those values into the second dropdown.
I recommend doing this with jQuery. It will make the experience much more pleasant. That being said:
var optionsMap = {
b: {
Kitchen: "Kitchen Side",
Closet: "Closet Side",
Full: "Full Room"
},
c: {
Window: "Window Side",
Door: "Door Side",
Full: "Full Room"
},
...
};
jQuery("#firstSelect").change(function() {
/* "this" is a reference to firstSelect element. Wrapping jQuery(...)
around it turns it into a jQuery object. Then you get the value
of the selected element with .val() */
var $select = jQuery(this);
var value = $select.val();
/* I'm doing the following to illustrate a point; in some cases
you may have to get it from a database with an AJAX request.
Basically YMMV */
var newOptions = optionsMap[value];
/* remove all the old options */
jQuery("#secondSelect").find("option").remove();
/* Iterate over the hash that you got and create new option
objects that use the key of the hash as the option value
and the value of the hash as the option text */
jQuery.each(newOptions, function(option, value) {
jQuery("#secondSelect").append(
jQuery("<option></option>").attr("value", option)
.text(value)
);
});
});
First, these kind of DOM modifying actions are made much easier with jQuery. It abstracts a lot of browser-specific crap away from you, making it much easier to do your thing. However, since you didn't mention the jQuery, I'll address the JavaScript issues. This is completely possible with JavaScript.
Second, you're going to want to give all of your select elements ids. This will make it much easier for JavaScript to identify them. Ids must be unique. I'm just going to follow the convention of naming the id after the name of the element.
Third, what we do is listen for the JavaScript event onchange on the select element and then do something with it (note the id attributes).
<select id="branch" name="branch" onchange="handleChange();">
<option value="b">Blacksburg</option>
<option value="c">Christiansburg</option>
<option value="f">Floyd</option>
<option value="m">Meadowbrook</option>
</select>
<select id="room" name="room">
</select>
The above code assigns the event listener handleChange to the branch select element. When a change event is fired, handleChange will be called. Now let's define the handleChange function:
<script type="text/javascript">
var handleChange = function() {
// get a handle to the branch select element
var branch = document.getElementById('branch');
// get the index of the selected item
var index = branch.selectedIndex;
// handle displaying the correct second select element
if (index === 0) {
// if the index is 0 (the first option,) call the Blacksburg function
doBlacksburg();
// I'll leave this up to you ;)
} else if (index === 1) {
// more stuff
}
}
</script>
Now we'll define the function that updates the second select list with Blacksburg information:
var doBlacksburg = function() {
var blacksburg = document.getElementById('room');
blacksburg.options[0] = new Option("Kitchen Side", "Kitchen", true, false);
blacksburg.options[1] = new Option("Closet Side", "Closet", false, false);
blacksburg.options[2] = new Option("Full Room", "Full", false, false);
}
That will update the second select list with the Blacksburg options. Reference for the JavaScript Option object.
That code is by no means extensive, but it should be enough to get you started. Like I said earlier, all of the above code can be done in as few as 5 lines of jQuery and it might be worth your time to look into jQuery or a similar library.
Are you familiar with / comfortable using a library like jQuery? I'd approach it with something like this:
var roomOpts = {
b: [
'<option value="Kitchen">Kitchen Side</option>',
'<option value="Closet">Closet Side</option>',
'<option value="Full">Full Room</option>'
]
....
};
$('select[name=branch]').change(function () {
$('select[name=room']).html(roomOpts[$(this).val()].join(''));
});
You can use an onchange event handler on the first list that calls a function to change the other list(s).
Look at this one:
http://www.webdeveloper.com/forum/showthread.php?t=97765