Remove selected option from select2 multiselect on change. - javascript

I have the following code. The aim is to style a select2 box with textbox as the searchbox. So I have implemented it as multiselect , but I only want one option to be selected.
One option is to restrict using maximumSelectionLength: 1. But in this case the limit message will be shown which i do not want to happen. (Even if i hide it some space will be taken up ).
Other option is to hide everything other than last-child , in that case multiple values will be send to backend when form is submitted.
So is there a way to remove the currently selected value when the new value is selected in multiselect ?
I'm using select2 version 3.5.2
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>

You can only keep the last selected item and remove all other. Like this way :
$('#placeSelect').click(function () {
var t = $("#placeSelect").val().substr($("#placeSelect").val().length - 1);
$("#placeSelect").val(t).trigger("change");
});
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>

$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: false,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>

You are using a multi option select, I suggest you to do the following:
multiple: false,

just add the following code in your query and it will work as you need it
$('ul.select2-choices').on("click", function() {
$("ul.select2-choices li .select2-search-choice-close").click();
});

Related

jQuery Select2 used from parent.window to child iframe

Good day all.
I have a html page, page.html, which loads an iframe, called iframe.html.
I have Select2 into page.html and there is a <select class='selectme'> into iframe.html.
I'm using this js to fire Select2 FROM page.html:
var jFrame = function (selector) { return $(selector, $("iframe").contents()); };
OurBigWrapper = {
"setup":{
"init":function(){
console.log("wrapper,setup,init");
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
jFrame(".countries").select2(
{
data: data /*,
formatSelection : this.formatSelection.bind(this)*/
}
);
}
}
}
while on the iframe.html page the code is like this:
<select class="countries">
</select>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
parent.OurBigWrapper.setup.init();
});
</script>
What I obtain is that the Select gets the data properly, but once clicked, the select only "change" the little arrow on the right, indicating the "opened option panel" but no option actually shows up.
interesting enough, if I delete the select2 css, this is what I obtain:
and here, clicking on the select and selecting another option, is what I see:
someone has any kind of clue of what is going on and how I can prevent it to happen?
<script>
$(function ($) {
$("button").on("click", function (evt) {
var jFrame = function (selector) { return $(selector, $("iframe").contents()); };
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
jFrame(".selectme").select2(
{
data: data
}
);
});
})
</script>
</head>
<body>
<iframe id="myframe" src="iframe.html"></iframe>
<button type="button">click</button>
</body>
and
<body>
<select class="selectme"></select> i
</body>
</html>

How to change background color select 2 using javascript?

Demo and my code is like this : http://jsfiddle.net/fc1qevem/10/
My javascript code is like this :
var select02 = $('#select02');
$(select02).select2({
data: [{
id: 0,
text: "test01"
}, {
id: 1,
text: "test02"
}, {
id: 2,
text: "test03"
}, {
id: 3,
text: "test04"
}, {
id: 4,
text: "test05"
}],
placeholder: "Branch name",
});
I want change the background color of select2 to blue color
I want change the background color using javascript
Whether it can be done?
Thank you
add this in your css
.select2-selection{
background-color:blue !important;
}
js solution
$(select02).select2({
data: [{
id: 0,
text: "test01"
}, {
id: 1,
text: "test02"
}, {
id: 2,
text: "test03"
}, {
id: 3,
text: "test04"
}, {
id: 4,
text: "test05"
}],
placeholder: "Branch name",
}).data("select2").$container.find(".select2-selection").css('background-color', 'blue');
When you will change the background-color using JavaScript try this:
$('.select2-selection').css('background-color', 'blue');
// Css code
.bg_color {
background-color: blue !important;
}
// Javascript code
// just put this code under the load function
$(select02).select2({ containerCssClass: "bg_color " });
This is how select2 adding class to the container or default css ".select2-container--default .select2-selection--single" of select2 where you can edit the background color of the container. Hope it helps you.
Try the code below:-
document.getElementById("select02").style.backgroundColor="blue";

Set "val" not working(pre selecting)

I have looked at multiple questions on SO and on Git hub:
Set multiple Select2 options
Select2 can't set multiple value
Is initSelection used for select2(val)
But I still cant seem to figure out why the values is not being set.
I am using a jinja2 template, so Ill give the generated html/js:
<div class="form-group">
<label class="control-label col-sm-4" for="message_type">Meassage Type</label>
<div class="col-sm-5">
<input type="hidden" name="message_type" id="message_type" readonly />
</div>
</div>
and the js:
$(function () {
$("#message_type").select2({
placeholder: "Email/SMS/PIMS Modal",
multiple: true,
width: "300px",
tokenSeparators: [',', ' '],
data: [{
id: "email",
text: "Email"
}, {
id: "pims modal",
text: "PIMS Modal"
}, {
id: "sms",
text: "SMS"
}, ],
});
$("#message_type").select2("val", "pims modal");
});
I have also managed to reproduce the result, see example.
The issue occurs because you have set the multiple property to true. In this case to set a value you need to use an array instead of a string.
For example:
$(function () {
$("#message_type").select2({
placeholder: "Email/SMS/PIMS Modal",
multiple: true,
width: "300px",
tokenSeparators: [',', ' '],
data: [{
id: "email",
text: "Email"
}, {
id: "pims modal",
text: "PIMS Modal"
}, {
id: "sms",
text: "SMS"
}, ],
});
$("#message_type").select2("val", ["email"]);
});
A working demo here: http://jsfiddle.net/nww22qoj/19/
Edit: Here is a working jsfiddle using the 4.0.1 version of the plugin http://jsfiddle.net/nww22qoj/20/ (using the full version of the plugin)

Identifying "Aria-Selected" State - Jquery

I'm using Kendo-UI's Drag and Drop Tree View for an application I'm working on.
I'm looking to append some text to the selected list-item.
I can not find anything in the documentation and am having a hard time selecting the appropriate item.
This is the Kendo-UI code:
<script>
$("#treeview-left").kendoTreeView({
dragAndDrop: true,
dataSource: [
{ text: "Furniture", expanded: true, items: [
{ text: "Tables & Chairs" },
{ text: "Sofas" },
{ text: "Occasional Furniture" }
] },
{ text: "Decor", items: [
{ text: "Bed Linen" },
{ text: "Curtains & Blinds" },
{ text: "Carpets" }
] }
]
});
$("#treeview-right").kendoTreeView({
dragAndDrop: true,
dataSource: [
{ text: "Storage", expanded: true, items: [
{ text: "Wall Shelving" },
{ text: "Floor Shelving" },
{ text: "Kids Storage" }
]
},
{ text: "Lights", items: [
{ text: "Ceiling" },
{ text: "Table" },
{ text: "Floor" }
]
}
]
});
</script>
This is a snippet of the generated code (notice the "aria-select='true'" , this is because I've selected the element, now I want to append text to this element):
<li role="treeitem" class="k-item" data-uid="82bceebe-f6a8-4d44-80ec-76f4b3db5041" aria-selected="true" id="treeview-left_tv_active">
<div class="k-top">
<span class="k-icon k-plus" role="presentation"></span>
<span class="k-in k-state-selected">Alberta</span>
</div>
<ul class="k-group" style="display:none" role="group">.....</ul>
</li>
This is my code at this point, I've tried a few other things, but have reverted back to this, which I know is incorrect:
<script>
$(function () {
$(".k-treeview li:first").click(function () {
$(this).append("test");
});
});
</script>
Any help is appreciated.
The aria attributes are for accessibility and not really meant to be used for other purposes.
You can use the select event and access the selected element in e.node:
$("#treeview").kendoTreeView({
dataSource: ds,
select: function(e) {
var model = this.dataItem(e.node);
model.set("text", model.get("text") + "test");
}
})
You can play with it here.
If you want to get the selected node at other times, use the select method.

Selecting rows from one grid & passing them to another grid

I'm trying to allow rows to be selected via checkboxes and for those selected rows and their IDs to be sent to another grid when a 'Submit' button is clicked. In other words, acting as some sort of filter.
I've contacted Telerik's support team and was advised to take the following steps in order to get it working:
Get the selected rows with the Select() method of the Grid
Loop through them & get the underlying item with the dataItem method
Save them into an array
Destroy the grid
Initialize a new grid by setting the data data
Here's a sample on JSBin that shows what I have in mind.
I'm not sure where to start honestly. I would really appreciate it if someone could point me in the right direction to any resources or guides that would be helpful. Thanks!
Assuming you are using RadGrid, make sure you have client side selection turned on, you would see something like this:
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowSelected="RowSelected" />
</ClientSettings>
On the input button, make sure to call your JS method as follows :
<input onclick="GetSelected();" .... >
Your JS code might look something like this :
function GetSelected() {
var grid = $find("<%=Your Grid's ClientID Here%>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems(); // 1. Get the selected rows. The selected item can be accessed by calling the get_selectedItems() method of the GridTableView client-side object.
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
// This is where you would have to insert it in a collection so that you can bind it to another grid... You will need to call .Rebind() once you assign the new datasource to the other grid.
}
Hopefully this will give you some idea.. I can see if I can find any examples on inserting rows into other grid if you get stuck.
check this code
html
<div id="grid1"></div>
<input type="button" value="Submit" onclick="Move()" />
<div id="grid2" ></div>
script
<script>
$(document).ready(function() {
var data1 = [
{ id: 1, rating: 3, year: 1997, title: "Rock" }
, { id: 2, rating: 5, year: 1999, title: "X-Man" }
, { id: 3, rating: 4, year: 2011, title: "World War Z" }
];
var grid1=$("#grid1").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ template: "<input type='checkbox' class='checkbox' />", width: "40px" }
,{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data1
}
}).data("kendoGrid");
grid1.table.on("click", ".checkbox", selectRow);
var data2 = [
{ id: 101, rating: 6, year: 2012, title: "The Impossible" }
, { id: 102, rating: 8, year: 2013, title: "Escape" }
, { id: 103, rating: 7, year: 2013, title: "Gravity" }
];
$("#grid2").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data2
}
});
});
function Move() {
var grid1 = $("#grid1").data("kendoGrid");
var rows = grid1.select();
rows.each(function(index, row) {
var selectedRow = grid1.dataItem(row);
//-move to grid2
var grid2 = $("#grid2").data("kendoGrid");
var ins = { id: selectedRow.id, rating: selectedRow.rating, year: selectedRow.year, title: selectedRow.title }; //id=1,rating=9.2,year=1995,title="The Godfather"
grid2.dataSource.insert(ins);
});
rows.each(function() {
grid1.removeRow($(this).closest('tr'));
});
}
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr");
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
</script>
this will help you :)

Categories

Resources