How to set selected to option using ddSlick after postback? - javascript

I need to use image drop-down list from http://designwithpc.com/plugins/ddslick I am trying to set "selected" option after postback, but I get infinite loop of postbacks. Here is my code:
<form id="form1">
<select id="localeId" name="localeId"></select>
</form>
<script type="text/javascript">
//Dropdown plugin data
var ddData = [
{
text: "English",
value: "en",
selected: false,
description: "English",
imageSrc: "/assets/img/flags-icons/en-flag.png"
},
{
text: "Portuguese",
value: "pt",
selected: false,
description: "Portuguese",
imageSrc: "/assets/img/flags-icons/pt-flag.png"
},
{
text: "Russian",
value: "ru",
selected: false,
description: "Russian",
imageSrc: "/assets/img/flags-icons/ru-flag.png"
},
{
text: "Spanish",
value: "es",
selected: false,
description: "Spanish",
imageSrc: "/assets/img/flags-icons/es-flag.png"
}
];
$('#localeId').ddslick({
data: ddData,
defaultSelectedIndex: 3,
onSelected: function (data) {
if (data.selectedIndex > 0) {
$('#hidCflag').val(data.selectedData.value);
$.cookie('lang', document.getElementById("hidCflag").value, { expires: 365 });
form1.submit();
}
}
});
</script>
Could please help me to solve it?

Calling:
$( '#demoSetSelected' ).ddslick( 'select', { index: i } );
will also trigger the "onSelected()" function you defined causing an infinite loop.
I solved the same problem by modifying the source file (jquery.ddslick.js) and adding a flag to disable the call to onSelected():
Change the select function to:
methods.select = function (options) {
return this.each(function () {
if (options.index)
selectIndex($(this), options.index, options.disableTrigger);
});
}
Modify selectIndex function definition from:
function selectIndex(obj, index) {
to:
function selectIndex(obj, index, disableTrigger) {
At the very end of the function selectIndex(...), change from:
if (typeof settings.onSelected == 'function') {
settings.onSelected.call(this, pluginData);
}
to:
if ( !disableTrigger ) {
if (typeof settings.onSelected == 'function') {
settings.onSelected.call(this, pluginData);
}
}
Then use instead:
$( '#demoSetSelected' ).ddslick( 'select', { index: i, disableTrigger: true } );
As an aside: to select by value instead of index, check out the code mentioned in:
https://github.com/prashantchaudhary/ddslick/issues/78
https://github.com/lunrfarsde/ddslick
It's a fork of dd-slick with the description part removed. But added select by value.

You may use plugin's select method like
$('#demoSetSelected').ddslick('select', {index: i });
to select a particular index.
As per ddSlick demo#4 on their website(http://designwithpc.com/plugins/ddslick#demo)

Related

Kendo MultiSelect make value to be selected and disable

Need help here. I create a simple demo here and what I want to achieve from dataBound if checked='yes' node is selected and disable(apply k-state-disable) from edit. I try to set (selected,true) & (disabled,true) but seem it not working.
DEMO IN DOJO
<select id="multiselect"></select>
$("#multiselect").kendoMultiSelect({
dataSource: {
data: [
{id:1, Name: "John 1", checked: 'no'},
{id:2, Name: "John 2", checked: 'yes'},
{id:3, Name: "John 3", checked: 'no'},
{id:4, Name: "John 4", checked: 'yes'},
{id:5, Name: "John 5", checked: 'no'},
{id:6, Name: "John 6", checked: 'no'}
]
},
dataTextField: "Name",
dataValueField: "id",
dataBound: function(e) {
var multiselect = $("#multiselect").data("kendoMultiSelect");
var x = multiselect.dataSource.view();
for (var i = 0; i < x.length; i++) {
if (x[i].checked == "yes") {
//x[i].set("selected", true);
//x[i].set("disabled ", true);
//x[i].prop("disabled", true).addClass("k-state-disabled");
}
}
},
});
I want to suggest another way for achieve that. Avoid changing DOM in dataBound whenever possible. So I would like to suggest using itemTemplate option and select event:
You can apply .k-state-disabled class within the itemTemplate option:
itemTemplate: '<span # if (data.checked === "yes") { #class="k-state-disabled"# } #>#: Name #</span>'
That will make the option look like disabled. But it is still possible to select it in the list, so you can use select event to prevent that:
select: function(e) {
if (e.dataItem.checked === 'yes') {
e.preventDefault();
}
},
Using e.preventDefault() inside that event will prevent user from selecting the option which matches the condition.
Updated Demo
You need to handle select and deselect events:
function onDeselect(e) {
if (e.dataItem.checked == 'yes') {
e.preventDefault();
}
}
function onSelect(e) {
if(e.dataItem.checked == 'yes') {
e.preventDefault();
}
};
$("#multiselect").kendoMultiSelect({
select: onSelect,
deselect: onDeselect,
//...
});
working demo

Kendo UI Grid - Custom command button disabled depending on boolean property

How can I set the class to disabled for a custom command on a Kendo grid depending on the boolean value of a property?
I want to use this approach to make the button disabled:
https://docs.telerik.com/kendo-ui/knowledge-base/disable-the-grid-command-buttons
Javascript:
{ command: { name: "custom", text: "Exclude", click: excludeCategorization }, title: " ", width: "60px" }
I want to add a condition like this using the property IsEnabled but if possible using the k-state-disabled class
#= IsEnabled ? disabled="disabled" : "" #
I don't believe you can assign classes conditionally through a template, however you can use the dataBound event to crawl through the rows and manipulate the classes. I would start with all of them disabled and then enable the ones that need to be active, but you can build your own logic. Here's an example:
<div id="grid"></div>
<script>
var grid;
$("#grid").kendoGrid({
dataBound:function(e){
var grid = $("#grid").data("kendoGrid");
var items = e.sender.items();
items.each(function (index) {
var dataItem = grid.dataItem(this);
$("tr[data-uid='" + dataItem.uid + "']").find(".excludeCategorization").each(function( index ) {
if(dataItem.isEnabled)
{
$(this).removeClass('k-state-disabled')
}
});
})
},
columns: [
{ field: "name" },
{ field: "enabled" },
{ command: [{ className: "k-state-disabled excludeCategorization", name: "destroy", text: "Remove" },{ className: "k-state-disabled", name: "edit", text: "Edit" }] }
],
editable: true,
dataSource: [ { name: "Jane Doe", isEnabled: false },{ name: "John Smith", isEnabled: true } ]
});
</script>
Here's a link to a Dojo: https://dojo.telerik.com/ubuneWOB

Javascript: unique location.href

Hi,
I am currently working on this autocomplete-searchbox, and as untutored I am when it comes to JavaScript i wonder: how do i give each value an specific unique link to another .html page? So that 'Desserts' links to page1.html & 'Snacks' to page2.html?
As you can see are all the values currently linking to location.href = "http://www.cnn.com"; but i want to give each value a specific location.href..
Best regards
$(function(){
var term = [
{ value: 'Desserts' },
{ value: 'Snacks'},
{ value: 'Drinks'},
{ value: 'Cheesecake'},
{ value: 'Cookies'},
];
$('#autocomplete').autocomplete({
lookup: term,
onSelect: function myFunction() {
location.href = "http://www.cnn.com";
}
});
});
I think this is the direction you want to head. If you post more of what you have I can give you a more specific answer
$(function(){
var term = [{
value: 'Desserts',
location: 'page1.html'
},{
value: 'Snacks',
location: 'page2.html'
}, {
value: 'Drinks',
location: 'page3.html'
}, {
value: 'Cheesecake',
location: 'page4.html'
}, {
value: 'Cookies',
location: 'page5.html'
},];
$('#autocomplete').autocomplete({
lookup: term,
onSelect: function myFunction(e) {
//Depending on how you trigger onSelect e.currentTarget.location
//may or may not work. but you should be able to start with e
//and work your way to finding location.
location.href = "http://www.cnn.com"+e.currentTarget.location;
}
});
});
Also you could look into a library with a built in autocomplete and the documentation that goes with it. JQuery have something you could look into here: http://jqueryui.com/autocomplete/#combobox

Select2.js: why is id the same as text on change for removed?

JSfiddle: http://jsfiddle.net/cjVSj/
I have a simple select2 with the range of possible tags set by the tags option and the preloaded tags set by values in the input field in the html.
When the on change event fires on the select2, the removed item seems to lose its id, reporting instead its text value.
To see the problem, adding a tag (e.g. west) correctly reports the added.id, but removing the existing east tags reports id = east, not 1356.
Any insight into how to gain access to the id of a tag upon removal?
HTML:
<script>
var tags = [{ "id": 1354, "text": "north", "restricted": false
}, {"id": 1355, "text": "south", "restricted": false
}, {"id": 1356, "text": "east", "restricted": false
}, {"id": 1357, "text": "west", "restricted": false
}];
</script>tags:
<input type="text" id="mytags" value="east" />
JS:
$(document).ready(function () {
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id)
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id)
}
});
});
There was an issue with your select2 declaration and syntax.
Further more, if you entered any other text, say "eas" or "test", your piece of code reflected that as it is. Check this scenario.
Updated fiddle: http://jsfiddle.net/ZBf5H/
To be specific, you did not give appropriate mapping to your tags. Please find how to access remote data in select 2 from here
The change of code is as below:
$(document).ready(function() {
var data=[{id:1354,text:'north',restricted:false},
{id:1356,text:'east',restricted:false},
{id:1357,text:'west',restricted:false},
{id:1355,text:'south',restricted:false}];
function format(item)
{ return item.text; }
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
data:{ results: data, text: 'text' },
formatSelection: format,
formatResult: format
});
Let me know if this works for you.
Ok... I've got a working solution, but I still don't exactly understand the difference between select2's tags and data options....
JSfiddle: http://jsfiddle.net/7e8Pa/
I'm initializing select2 with a list of all possible tags via the data option from an array, then selecting those for preloading: the initSelection function checks for ids in the and looks them up in the data array (the pre-stored one, not Select2's). Last, new tags may be added (the createSearchChoice does this). To hook this to my server, I'm just going to insert ajax calls where noted below in the on-change event handler (which gets called after createSearchChoice, and can overwrite the field values for the new object set in createSearchChoice).
JS:
function findWithAttr(array, attr, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] == value) {
return array[i];
}
}
}
$(document).ready(function () {
function format(item) {
return item.text;
}
$('#mytags').select2({
placeholder: 'Search',
minimumInputLength: 2,
multiple: true,
//tags: tags,
tokenSeparators: [','],
data: {
results: tags,
text: 'text'
},
initSelection: function (element, callback) {
var data = [];
$($('#mytags').val().split(",")).each(function (i) {
var o = findWithAttr(tags, 'id', this);
if (o) {
data.push({
id: o.id,
text: o.text
});
} else {
console.log("findWithAttr returned none; likely invalid id");
}
});
console.log("data = " + JSON.stringify(data));
callback(data);
},
createSearchChoice: function (term, data) {
console.log("create");
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// call $.post() to add this term to the server, receive back id
// return {id:id, text:term}
// or detect this shiftiness and do it below in the on-change
return {
id: -1,
text: term
};
}
},
formatSelection: format,
formatResult: format
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id);
//modifying the id here overrides what is assigned above in createSelection
e.added.id = 5;
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id);
}
var selections = (JSON.stringify($('#mytags').select2('data')));
$('#selectedText').text(selections);
});
});
HTML:
<script>
var tags = [{
"id": 1354,
"text": "north",
"restricted": false
}, {
"id": 1355,
"text": "south",
"restricted": false
}, {
"id": 1356,
"text": "east",
"restricted": false
}, {
"id": 1357,
"text": "west",
"restricted": false
}];
</script>
<p>tags:
<input type="text" id="mytags" value="1355" style="width:80%" />
</p>
<p>Selected Options: <span id="selectedText"></span>
</p>
<p>Debug: <span id="debug"></span>
</p>

Select2 multiselect duplicates values

http://jsfiddle.net/tXFbk/2/
HTML:
<div class="control-group">
<label for="some_id" class="control-label">Some ID</label>
<div class="controls">
<input type="text" id="some_id" name="some_id" class="span4"/>
</div>
</div>
JS:
$(function() {
$('#some_id').select2({
allowClear: true,
placeholder: 'Some ID',
minimumInputLength: 2,
multiple: true,
data: [
{id: 1, text: 'some text'},
{id: 2, text: 'some other text'},
{id: 3, text: 'some more text'}
]
});
$('#some_id').select2('data', [
{'id':1,'text':'some text'}
]);
console.log($('#some_id').select2('val'));
});
On first load it duplicates values and after clearing value it doesn't clear it from input. Also if you add an item (eg. "some more text") and then remove it, it doesn't clear it from input value. Is there any way to make it stop duplicating values?
One more thing - how to disable adding already added items?
Select2 4.0.0 support duplicate tags.
Jsfiddle Demo link
$eventSelect.on("select2:select", function (e) {
log("select2:select", e);
$eventSelect.append('<option value="'+e.params.data.text+'">' +e.params.data.text + '</option>');
});
$eventSelect.on("select2:unselect", function (e) {
log("select2:unselect", e);
e.params.data.element.remove();
});
function formatResultData (data) {
if (!data.id) return data.text;
if (data.element.selected) return
return data.text;
};
Base on select2 event and github issues
Pic:
Check the following On Selecting event, and setting the isNew property in createSearchChoice
let me know if it resolved your issue
$('#some_id').select2({
tags: true,
tokenSeparators: [","],
createSearchChoice: function (term, data) {
if (term.trim().length > 0) {
if ($(data).filter(function () {
return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0;
}).length === 0) {
return {
id: term,
text: term,
isNew: true // this is necessary to check if the item is newly added or not
};
}
}
},
multiple: true,
minimumInputLength: 1,
allowClear: true,
data: [
{id: 1, text: 'some text'},
{id: 2, text: 'some other text'},
{id: 3, text: 'some more text'}
],
}).on("select2-selecting", function (e) {
var tagId = '';
if (e.choice.isNew) {
self.AddTagToDatabase(e.choice.text);
} else {
var isValidTag = true;
$(config.element[0] + ' ul li').find('div').each(function (index, item) {
if ($(item).html().toLowerCase().trim() == e.choice.text.toLowerCase().trim()) {
isValidTag = false;
e.choice.text = '';
return;
}
});
}
})
You need to trigger the change event of select2 to reflect the changes.
$("#dropdownId").val("yourValues").trigger("change");
after setting the values, you need to fire trigger values manually, to reflect the latest changes done in your dropdownlist

Categories