Highlight selected jsGrid row - javascript

I found this example which highlights a row after it has been selected but the problem with it is that it keeps the previous row(s) highlighted after another one has been selected.
Here's part of the code
//js
rowClick: function(args) {
var $row = this.rowByItem(args.item);
$row.toggleClass("highlight");
},
//css
tr.highlight td.jsgrid-cell {
background-color: green;
}
I can't find a solution to unhighlight the previously selected row

A little late to the party on this one, however the accepted answer by #Narenda didn't completely solve my problem. This may help someone else that stumbles across this later.
If you need a single select only, here's a way of doing it:
Extend the jsGrid plugin with a method to find a row by index:
jsGrid.Grid.prototype.rowByIndex = function(arg){
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
Modify the rowClick function in #Narenda's answer:
rowClick: function ( args ) {
//Deselect all rows
for(var i = 0; i<this.data.length; i++){
this.rowByIndex(i).removeClass("jsgrid-highlight-row");
}
//Everything else as per the previous answer
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.jsgrid-highlight-row');
if (selectedRow.length) {
selectedRow.toggleClass('jsgrid-highlight-row');
};
$row.toggleClass("jsgrid-highlight-row");
//Any other code to run on item click
}
And add some CSS. This mimics the row hover in the default theme:
tr.jsgrid-highlight-row td.jsgrid-cell {
background:#c4e2ff;
border-color:#c4e2ff;
}

You can achieve by this following steps
First on row click you need to get selected row like this
var selectedRow = $("#jsGrid").find('table tr.highlight').
Then you can use
selectedRow.toggleClass('highlight') or selectedRow.removeClass('highlight')
DEMO
$("#jsGrid").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method Need to set auto load true
autoload: true,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
var data = [{
nickname: "Test",
email: "t#gmail.com"
}, {
nickname: "Test 1",
email: "t1#gmail.com"
}, {
nickname: "Test 2",
email: "t2#gmail.com"
}, {
nickname: "Test 3",
email: "t3#gmail.com"
}];
return data;
}
},
rowClick: function(args) {
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.highlight');
if (selectedRow.length) {
selectedRow.toggleClass('highlight');
};
$row.toggleClass("highlight");
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
tr.highlight td.jsgrid-cell {
background-color: green;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>

If you came looking for a solution in which only 1 line is selected and which also deselects the same line, here is the solution:
selectedVal = null;
$(document).ready(function(){
jsGrid.Grid.prototype.rowByIndex = function(arg) {
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
});
rowClick: function (args) {
selectedVal = args.item;
let $row = this.rowByItem(args.item);
if ($row.hasClass("highlight") === false) {
//Deseleciona todas as linhas
for (let i = 0; i < this.data.length; i++) {
this.rowByIndex(i).removeClass("highlight");
}
$row.toggleClass("highlight");
} else {
selectedVal = null;
$row.toggleClass("highlight");
}
console.log(selectedVal);
}

Related

jQuery Autocomplete rendertem__ Cant Return Value Within If Statement

Trying to render a search list with jQuery Autocomplete however my goal is that once a list item is appended to the page (a user selects an item, and a user can select multiple items) the user is unable to search for that same item.
HTML CODE
<div id='feature-searchbar'>
<label for='feature-search'>Search for applicable features...</label>
<input id="feature-search-input" type="text" name="featureSearch-input" placeholder="Search for applicable features..." class="feature__search-input ui-autocomplete-input" autocomplete="off">
<div id='feature-results'>
//Selected items go here
</div>
</div>
Right now trying to go about it by adding a class to a rendered item if it is already present in the appended page. Using jQuery I target the on the page where the items will appear if a user were to select one and target the data-type. Tell my jQuery 'if the datatype is already present, add a class' however I cant seem to return the value outside of the if statement.
jQuery
jQuery("#feature-search-input").autocomplete({
appendTo: "#feature-searchbar",
source: function (req, res) {
jQuery.ajax({
url: myAPI
data: {
term: jQuery("#feature-search-input").val(),
},
type: "GET",
datatype: 'json',
crossOrigin: true,
success: function (data) {
// set results to top 6 only
data.length = Math.min(data.length, 5);
var items = data;
var search_term = jQuery("#feature-search-input").val();
items.push({
label: `<?php _e('More search results for'); ?> "${ search_term }"`,
value: search_term,
more_results: true
});
res(items);
}
});
},
select: function(event, ui) {
var featureListItem = `<div class="feature-list-item" data-id="${ui.item.id}">
<input type='hidden' name='content-feature-ids[]' value='${ui.item.id}'>
<p>${ ui.item.short_desc }</p>
<a class='content-feature-remove'>Remove<a/>
</div>`;
//append to page
jQuery('#feature-results').append(featureListItem);
//removal
jQuery(".content-feature-remove").click(function (e) {
jQuery(this).parent().remove();
});
jQuery("#feature-search-input").val('');
}
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
//TODO: check if item exists within feature-results, do not render it
//if item is rendered onto feature-results { add: class which tells user it has already been selected}
var item_label = '';
//need to validate items somehow so they do not get selected twice
if (item.id && item.short_desc) {
item_label = `
<div class='rendered-feature-item' data-id="${item.id}">
<p>${ item.short_desc }</p>
</div>
`;
} else {
item_label = `<strong>No Results</strong>`;
}
//need to validate items somehow so they do not get selected twice
//target the html and check if data-type is same as item.id
var existing_feature = jQuery(`#feature-results .feature-list-item[data-id="${item.id}"]`)
var existing_feature_id = 0;
var variable = '';
if (existing_feature !== undefined && existing_feature !== null) {
existing_feature_id = existing_feature.data('id');
if (existing_feature_id !== undefined && existing_feature_id !== null) {
console.log(existing_feature_id);
var potential_existing = jQuery('.rendered-feature-item[data-id="'+existing_feature_id+'"]');
var potential_existing_id = potential_existing;
return existing_feature_id;
}
return existing_feature_id;
}
//here is where I get errors, code does not recognize existing_feature_id
var potential_existing_id = existing_feature_id
var potential_existing_item = jQuery('.rendered-feature-item[data-id="'+potential_existing_id+'"]')
potential_existing_item.css('color', 'red');
return jQuery( '<li>' )
.attr( "data-value", item.id )
.append( item_label )
.appendTo( ul );
};
});
Reason I have to run a if statement is that the id variable is coming back as the id however also as "undefined" at the same time
Currently getting an error that states
Uncaught TypeError: this._renderItem(...).data is not a function
Consider the following example. This is loosely related to https://jqueryui.com/autocomplete/#multiple
jQuery(function($) {
var availableFeatures = [{
label: "ActionScript",
value: "ActionScript",
id: "1"
},
{
label: "AppleScript",
value: "AppleScript",
id: "2"
},
{
label: "Asp",
value: "Asp",
id: "3"
},
{
label: "BASIC",
value: "BASIC",
id: "4"
},
{
label: "C",
value: "C",
id: "5"
}
];
function getFeatures(apiUrl, searchTerm) {
var results;
$.ajax({
url: apiUrl,
data: {
term: searchTerm,
},
type: "GET",
datatype: 'json',
crossOrigin: true,
success: function(data) {
results = data;
}
});
return results;
}
function filterResults(fArr, results) {
$.each(fArr, function(i, el) {
var index = results.map(function(e) {
return e.label;
}).indexOf(el);
if (index > -1) {
results.splice(index, 1);
}
});
return results;
}
function getCurrentFeatures(target) {
var features = [];
$(".feature-list-item", target).each(function(i, el) {
features.push($("p", el).text().trim());
});
return features;
}
function addFeature(item) {
var featureItem = $("<div>", {
class: "feature-list-item"
}).data("feature-id", item.id);
$("<p>").html(item.label).appendTo(featureItem);
$("<a>", {
class: "content-feature-remove",
title: "Remove Feature"
}).html("X").appendTo(featureItem);
$("#feature-results").append(featureItem);
if ($("#selectedFeatures").val() == "") {
$("#selectedFeatures").val(item.id);
} else {
var selected = $("#selectedFeatures").val().split(",");
selected.push(item.id);
$("#selectedFeatures").val(selected.join(","));
}
}
function removeFeature(item) {
var thisId = $(item).closest(".feature-list-item").data("feature-id");
console.log("Remove Feature", thisId);
$(item).parent().remove();
var selected = $("#selectedFeatures").val().split(",");
var index = selected.indexOf(thisId);
console.log(selected, index);
if (index > -1) {
selected.splice(index, 1);
}
$("#selectedFeatures").val(selected.join(","));
}
$("#feature-search-input").autocomplete({
source: function(request, response) {
// Example og getting data
// var myData = getFeatures("/results", request.term);
var myData = availableFeatures;
myData = filterResults(getCurrentFeatures("#feature-results"), myData);
myData = $.ui.autocomplete.filter(myData, request.term);
response(myData);
},
focus: function() {
return false;
},
select: function(e, ui) {
addFeature(ui.item);
$(this).val("").autocomplete("search", "");
return false;
}
});
$("#feature-results").on("click", ".content-feature-remove", function(event) {
event.preventDefault();
removeFeature(this);
});
/*$("#feature-search-input").autocomplete({
appendTo: "#feature-searchbar",
source: function(req, res) {
$.ajax({
url: myAPI
data: {
term: $("#feature-search-input").val(),
},
type: "GET",
datatype: 'json',
crossOrigin: true,
success: function(data) {
var items = [];
items.push({
label: data.label,
value: data.value
});
res(items);
}
});
},
select: function(event, ui) {
var featureListItem = `<div class="feature-list-item" data-id="${ui.item.id}"><input type='hidden' name='content-feature-ids[]' value='${ui.item.id}'><p>${ ui.item.short_desc }</p><a class='content-feature-remove'>Remove<a/></div>`;
$('#feature-results').append(featureListItem);
$(".content-feature-remove").click(function(e) {
$(this).parent().remove();
});
$("#feature-search-input").val('');
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var item_label = '';
if (item.id && item.short_desc) {
item_label = `<div class='rendered-feature-item' data-id="${item.id}"><p>${ item.short_desc }</p></div>`;
} else {
item_label = `<strong>No Results</strong>`;
}
var existing_feature = $(`#feature-results .feature-list-item[data-id="${item.id}"]`);
var existing_feature_id = 0;
var variable = '';
if (existing_feature !== undefined && existing_feature !== null) {
existing_feature_id = existing_feature.data('id');
if (existing_feature_id !== undefined && existing_feature_id !== null) {
console.log(existing_feature_id);
var potential_existing = jQuery('.rendered-feature-item[data-id="' + existing_feature_id + '"]');
var potential_existing_id = potential_existing;
return existing_feature_id;
}
return existing_feature_id;
}
var potential_existing_id = existing_feature_id
var potential_existing_item = jQuery('.rendered-feature-item[data-id="' + potential_existing_id + '"]')
potential_existing_item.css('color', 'red');
return jQuery('<li>')
.attr("data-value", item.id)
.append(item_label)
.appendTo(ul);
};
*/
});
.feature-list-item {
border: 1px solid #9f9f9f;
border-radius: 6px;
display: inline-block;
padding: 3px 6px;
margin-right: 3px;
}
.feature-list-item p {
display: inline-block;
font-size: 11px;
font-family: sans-serif;
padding: 0;
margin: 0;
padding-right: 3px;
color: #2f2f2f;
}
.content-feature-remove {
font-size: 10px;
font-family: sans-serif;
font-weight: bold;
display: inline-block;
color: #999;
border: 1px solid #999;
border-radius: 50%;
width: 12px;
height: 12px;
text-align: center;
cursor: pointer;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='feature-searchbar'>
<label for='feature-search'>Search for applicable features...</label>
<input id="feature-search-input" type="text" name="featureSearch-input" placeholder="Search for applicable features..." class="feature__search-input ui-autocomplete-input" autocomplete="off">
<div id='feature-results'></div>
<input id="selectedFeatures" type="hidden" name="content-feature-ids" />
</div>
Considering that your AJAX will come back with an Array of Objects, I setup the example to work on this case.
When the User selects an item, it adds it to a list, and updates a text field. As more items are added or removed, the text field is updated with the IDs for each feature.
The suggestion list will filter the results and will exclude any that have already been selected.
The snippet cannot show AJAX. You will see a function to help get the data from PHP. Run it like so:
var myFeatures = getFeatures("/features.php", "feature");
This will perform a GET request of the URL supplied with the search term. Your PHP will want to return an Array of Objects:
[{
label: "Feature 1",
value: "Feature 1"
id: "f001"
}];
You can have more parameters than 'id' if you want, yet you must have label and value for autocomplete.
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
My example makes use of the following line:
myData = $.ui.autocomplete.filter(myData, request.term);
You can omit this line in your script as PHP should be filtering the results for you.

How to get selected checkbox based on first selected dropdown after refresh the page?

I have dropdown, checkboxes and button submit. First, the user will choose at dropdown (position of work). Second, the user will select the checkbox and after that submit the data. Here, after refresh it should be appear back the previous selected dropdown and checkbox. But, I did not get it. Anyone here have more better solution?
JavaScript Dropdown
//dropdown position
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "../DesignationProgramTemplate/getData.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: onChange
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
Checkbox treeview (Kendo UI)
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json"
}
},
schema: {
model: {
id : "ehorsProgramID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
// select: onSelect,
dataSource: homogeneous,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","ehorsProgramName"]
});
AJAX for submit button
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/getTemplate.php",
type: "post",
data: {'id':test,'progid':array},
success: function () {
// you will get response from your php page (what you echo or print)
kendo.alert('Success'); // alert notification
//refresh
//location.reload("http://hq-global.winx.ehors.com:9280/ehors/HumanResource/EmployeeManagement/DesignationProgramTemplate/template.php");
},
});
});
JavaScript for check checkboxes
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
var array = [];
function onCheck() {
var checkedNodes = [],treeView = $("#AccountingTree").data("kendoTreeView"),message;
var checkedNodes2 = [],treeView2 = $("#AdminSystemTree").data("kendoTreeView"),message;
var checkedNodes3 = [],treeView3 = $("#FnBTree").data("kendoTreeView"),message;
var checkedNodes4 = [],treeView4 = $("#HumanResourceTree").data("kendoTreeView"),message;
var checkedNodes5 = [],treeView5 = $("#InventoryManagementTree").data("kendoTreeView"),message;
var checkedNodes6 = [],treeView6 = $("#SalesMarketingTree").data("kendoTreeView"),message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
checkedNodeIds(treeView2.dataSource.view(), checkedNodes);
checkedNodeIds(treeView3.dataSource.view(), checkedNodes);
checkedNodeIds(treeView4.dataSource.view(), checkedNodes);
checkedNodeIds(treeView5.dataSource.view(), checkedNodes);
checkedNodeIds(treeView6.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = checkedNodes.filter(x => !!x).join(",");
array = checkedNodes.filter(x => !!x);
} else {
message = "No nodes checked.";
}
}
Output
JavaScript for accessing the dataItem
// cookies
var values = ["LA1","LA6","LA12"]; //array nnti array ni la localstorage/cookies
var setTreeViewValues = function(values) {
var tv = $("#AccountingTree").data("kendoTreeView");
document.write(JSON.stringify(tv));
tv.forEach(function(dataItem) {
alert("test");
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
//document.write(JSON.stringify(childItems[0].items[0].programID));
}
// document.write(JSON.stringify(dataItem.items));
if (values.indexOf(childItems[0].items[0].programID) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
console.log(datasource.data()[0].hasChildren);
// end cookies
So without knowing how you are binding the existing values to the page I am assuming you will be calling the page state somewhere within your Page loading.
So I have prepared a dojo that shows two different ways of setting the checked state of the items.
https://dojo.telerik.com/EhaMIDAt/8
1. Setting at the DataSource Level
So when setting up the datasource you can add an extra attribute to your collection called checked this will then set the checked value for the item or children items when loaded. using the example I have in the dojo:
{
id: 9,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
id: 10,
text: "February.pdf",
spriteCssClass: "pdf"
},
{
id: 11,
text: "March.pdf",
spriteCssClass: "pdf",
checked: true
},
{
id: 12,
text: "April.pdf",
spriteCssClass: "pdf"
}
]
}
this will set the checked state to true for you and show the checkbox as checked.
2. Manually Set the values after loading all the DataSources.
So I have done this on a button click but this could easily be done on a ready state or some other trigger if needed. Here the button when clicked will find the node in the tree with the text Research.pdf and either set it in a checked or unchecked state for you.
$('#checked').bind('click', () => {
var box = $("#treeview").data("kendoTreeView").findByText('Research.pdf').find('input[type="checkbox"]');
box.prop('checked', !box.is(':checked'));
});
Again the sample it taken from dojo link above. Hopefully this gives you a start on getting the values set according to your specific requirements.
I would probably have the value checked state set when you load the datasource for the treeview.

Generating TinyMCE drop-down menu dynamically

I am trying to create toolbar button in TinyMCE with options that are derived from the array. I've followed the examples on Tiny's website and the button is getting generated as expected. Here is the code:
var mergeFields = {one: "first", two: "second", three: "third"};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function (editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function (callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
onAction: function() {
// The problem: this function always inserts the last element of the array
// instead of the expected fieldName associated with this menuItem
editor.insertContent(fieldName);
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});
<script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=XXXXX"></script>
<textarea>Editor</textarea>
The problem happens when one of the options is selected and the anonymous function assigned to onAction property is executed -- it always inserts "three" into the document (presumably because after running through the whole array, fieldName is set to "three"). How can I make the onAction handler insert the right value into the document?
This needs to work in TinyMCE 5.
I've found a similar question here: Adding custom dropdown menu to tinyMCE and insert dynamic contents, but it was referring to TinyMCE 4 and unfortunately the provided answer does not work for TinyMCE 5.
Thanks for your help!
I had the same problem.
I solved it using value+onSetup
https://jsfiddle.net/stvakis/tjh7k20v/8/
var mergeFields = {
one: "first",
two: "second",
three: "third"
};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function(editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function(callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
value:fieldName,
onSetup: function(buttonApi) {
var $this = this;
this.onAction = function() {
editor.insertContent($this.data.value);
};
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});

Unable to create a delete button in Meteor using reactive-table

I building a sortable table in Meteor with Reactive-Table and having trouble getting my delete button to work for removing entries from the table.
Please see my javascript code below:
Movies = new Meteor.Collection("movies");
if (Meteor.isClient) {
Template.body.events({
"submit .new-movie": function (event) {
var title = event.target.title.value;
var year = event.target.year.value;
var genre = event.target.genre.value;
Movies.insert({
title: title,
year: year,
genre: genre
});
event.target.title.value = "";
event.target.year.value = "";
event.target.genre.value = "0";
return false;
}
});
Template.moviestable.events({
"click .deletebtn": function (event) {
Movies.remove(this._id);
}
});
Template.moviestable.helpers({
movies : function () {
return Movies.find();
},
tableSettings : function () {
return {
showFilter: false,
fields: [
{ key: 'title', label: 'Movie Title' },
{ key: 'year', label: 'Release Year' },
{ key: 'genre', label: 'Genre' },
{ key: 'edit', label: 'Edit', fn: function () { return new Spacebars.SafeString('<button type="button" class="editbtn">Edit</button>') } },
{ key: 'delete', label: 'Delete', fn: function () { return new Spacebars.SafeString('<button type="button" class="deletebtn">Delete</button>') } }
]
}
}
});
}
Can anyone tell me what I'm doing wrong?
In the reactive tables docs, there's an example of how to delete rows from the table. Adapting the example in the docs for your needs, your event should look like this:
Template.moviestable.events({
'click .reactive-table tbody tr': function (event) {
event.preventDefault();
var objToDelete = this;
// checks if the actual clicked element has the class `deletebtn `
if (event.target.className == "deletebtn") {
Movies.remove(objToDelete._id)
}
}
});
The problem you are having is that you are trying to find the _id property on the button click instead of the row click.
If you do console.log(this) on your button click event (as you have it in your question above) you will get something like this Object {key: "delete", label: "", fieldId: "2", sortOrder: ReactiveVar, sortDirection: ReactiveVar} which does not contain the property _id
It is easier to register the row click, where the row object is the actual document you are trying to delete, and then check if the event's target has the delete class you added.

Select2 - avoiding duplicates tags

How can I avoiding duplicates tags in Select2 input?
When I type tag name on the keyboard string is added to input field, but when I select tag from dropdown list (results from the database) the id is added to input (look at console.log on screenshot). So I can select tag from list and add the same tag from keyboard.
Moreover, I need the text of tags, not id from dropdown list while submit a form.
Full resolution
HTML:
<input type="hidden" id="categories" name="categories" style="width:100%" value="${categories}">
JS:
$("#categories").select2({
tags: true,
tokenSeparators: [","],
placeholder: "Dodaj",
multiple: false,
minimumInputLength: 3,
maximumInputLength: 50,
maximumSelectionSize: 20,
ajax: {
quietMillis: 150,
url: '${request.route_url("select2")}',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {results: data.categories, more: more};
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
createSearchChoice: function (term) {
return { id: term, text: term };
},
}).change(function (e) {
if (e.added) {
console.log($("#categories").val())
console.log(e)
}
});
Have same problem, but I figured it out to find a way around.
I'm getting text and ids, but on the server side I'm creating from given id new objects, which are well read.
$tagsArray = explode(',', $tagNames); // it contains of my input select2 value (with ids)
foreach ($tagsArray as $tag)
{
if (is_numeric($tag))
{
$tags->append(TagQuery::create()->filterById($tag)->findOneOrCreate());
}
elseif (!empty($tag))
{
$tags->append(TagQuery::create()->filterByName($tag)->findOneOrCreate());
}
}
Hope it helps.
at first use select 2
and then do this:
$("select").change(function() { var tr = $(this).closest("tr");
tr.find("select option").attr("disabled",""); //enable everything
//collect the values from selected;
var arr = $.map
(
tr.find("select option:selected"), function(n)
{
return n.value;
}
);
//disable elements
tr.find("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
}).attr("disabled","disabled"); });

Categories

Resources