Telerik Forums
Kendo UI for jQuery Forum
1 answer
696 views

I am using a dropdownlist widget in an ajax form used to edit an object. When the form loads, I need to initialize the dropdown, set its datasource, and programmatically set the selected dropdown item based on two values (compound key). However,  the return statement in my ddAssignee.select(function()) does not execute, so nothing gets selected. I checked the contents of ddAssignee.dataSource.view() immediately after calling setDataSource() and it was empty, so I'm assuming this is why nothing gets selected. However, I have a separate button that is  used to select the dropdown item after the form loads ("Take It" button), which works fine. I'm just trying to figure out what is missing after setting the datasource that is causing the dataSource.view() to still be empty. 

UPDATE: I overlooked this info about select(): 

  • If the widget is not bound (e.g. autoBind is set to false), the select method will not pre-fetch the data before continuing with the selection and value setting (unlike the value method), and no item will be selected.

            However, setting autoBind to true still does not solve the problem.

I have attached:

-Screenshot of the edit form

-Edit form html with ajax form

-InitAssigneeDropdown() basic dropdown initialization

-GetAllAssigneesDataSource() returns the remote data for the dropdown via kendo.data.DataSource

- onEditTask function (executes when button is clicked to open the edit form - where issue happens)

- "Take It" button event (where select(function()) works successfully)

Any help is greatly appreciated. Thanks! 


@model Models.Tasking.TaskModel

<div class="modal-content">

    @using (Ajax.BeginForm("SaveEditTask", "Tasking", null, new AjaxOptions()
    {
        UpdateTargetId = "frmEditTask",
        InsertionMode = InsertionMode.Replace,
        OnSuccess = "taskingSaveSuccess"
    }, new { id = "frmEditTask", autocomplete = "off" }))
    {
        <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">Edit Task</h5>
        </div>
        <div class="modal-body" style="max-height:70vh; overflow-y:auto">
            @Html.AntiForgeryToken()

            @Html.ValidationSummary(false, "", new { @class = "text-danger" })

            @Html.HiddenFor(m => m.ID)
            @Html.HiddenFor(m => m.PtOID)
            @Html.HiddenFor(m => m.PtMRN)
            @Html.HiddenFor(m => m.CreatedByUserFK)
            @Html.HiddenFor(m => m.CreatedDTTM)

            <div class="form-group">
                @Html.LabelFor(m => m.PtFullName, new { @class = "text-dark font-weight-bold" })
                @Html.TextBoxFor(m => m.PtFullName, new { @class = "form-control mb-2", @readonly = "readonly" })
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.TypeFK, new { @class = "text-dark font-weight-bold" })
                @Html.DropDownListFor(m => m.TypeFK, (IList<SelectListItem>)ViewBag.TaskTypeOptions, new { @class = "form-control p-1 w-auto mb-2", @disabled = "disabled", @readonly = "readonly" })
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.StatusFK, new { @class = "text-dark font-weight-bold" })
                <br />
                @Html.DropDownListFor(m => m.StatusFK, (IList<SelectListItem>)ViewBag.TaskStatusOptions, new { @id = "ddTaskStatusType", @class = "form-control p-1 w-auto mb-2" })
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.PriorityFK, new { @class = "text-dark font-weight-bold" })
                <br />
                @Html.DropDownListFor(m => m.PriorityFK, (IList<SelectListItem>)ViewBag.TaskPriorityOptions, new { @id = "ddTaskPriorityType", @class = "form-control p-1 w-auto mb-2", data_default_due_date_url = Url.Action("GetDefaultDueDate", "Tasking", new { area = "" }) })
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.DueDTTM, new { @class = "text-dark font-weight-bold" })
                @if (Model.CreatedByUserFK == User.Identity.GetUserId())
                {
                    @(Html.Kendo().DateTimePickerFor(m => m.DueDTTM).HtmlAttributes(new { @id="dtpTaskDueDate", data_toggle = "tooltip", data_placement = "bottom", data_trigger = "focus", required = "required" }))
                }
                else
                {
                    @Html.TextBoxFor(m => m.DueDTTM, new { @class = "form-control mb-2", @readonly = "readonly" })
                }
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.AssigneeFK, new { @class = "text-dark font-weight-bold" })
                <br />
                <div class="row">
                    <div class="col-9 pr-0">
                        <select id="ddTaskAssignee" name="AssigneeFK" data-all-assignees-url="@Url.Action("GetAllTaskAssigneeOptions", "Tasking", new { area = "" })" />
                    </div>
                    <div class="col-3 pl-2">
                        <button id="btnSelfAssignTask" type="button" class="btn btn-secondary" data-user-id-url="@Url.Action("GetUserId", "Tasking", new { area = "" })">Take It</button>
                    </div>
                </div>
                @Html.HiddenFor(m => m.AssigneeTypeFK, new { @id = "hiddenAssigneeTypeFK" })
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Description, new { @class = "text-dark font-weight-bold" })
                @if (Model.CreatedByUserFK == User.Identity.GetUserId())
                {
                    @Html.TextAreaFor(m => m.Description, new { @class = "form-control" })
                }
                else
                {
                    @Html.TextAreaFor(m => m.Description, new { @class = "form-control", @readonly = "readonly" })
                }
            </div>

        </div>

        <div class="modal-footer">
            @if (Model.CreatedByUserFK == User.Identity.GetUserId())
            {
                <button id="btnDeleteTask" type="button" class="btn btn-danger" data-target-url="@Url.Action("DeleteTask", "Tasking", new { area = "" })">Delete Task</button>
            }
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }

</div>
function initAssigneeDropDown() {
    $("#ddTaskAssignee").kendoDropDownList({
        optionLabel: 'Select Assignee ...',
        filter: "contains",
        dataTextField: 'AssigneeName',
        dataValueField: 'AssigneeFK',
        template: function (dataItem) {
            //TODO - improve logic
            if (dataItem.AssigneeTypeFK == 1)
                return '<span><i class="fas fa-user pr-2"></i>' + dataItem.AssigneeName + '</span>';
            else if (dataItem.AssigneeTypeFK == 2)
                return '<span><i class="fas fa-users pr-2"></i>' + dataItem.AssigneeName + '</span>';
        }
    });
}
function getAllAssigneesDataSource() {
    var url = $('#ddTaskAssignee').data('all-assignees-url');

    var dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                type: "POST",
                url: url
            }
        }
    });

    return dataSource;
}
function onEditTask(e) {
    //Fetch the ID, assigneeTypeFK, and assigneeFK from the grid item that's getting edited
    var grid = $('#taskGrid').data('kendoGrid');
    var taskDataItem = grid.dataItem($(e).closest("tr"));
    var taskId = taskDataItem.ID;
    var assigneeTypeFK = taskDataItem.AssigneeTypeFK;
    var assigneeFK = taskDataItem.AssigneeFK; 

    $('#taskModal').modal('show'); //Show the edit modal

    $('#taskModal .modal-content').html(''); //Clear out the modal container

    //ajax to return partial view for editing task
    $.ajax({
        url: $(e).data("target-url"), 
        type: "POST",
        cache: false,
        data: JSON.stringify({ taskId: taskId }), //Pass the task id to controller
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            $('#taskModal .modal-content').replaceWith(response); //add edit view html to modal

            initAssigneeDropDown();
            var ddAssignee = $('#ddTaskAssignee').data('kendoDropDownList');
            ddAssignee.setDataSource(dataSource);
            var assigneeDataSourceView = ddAssignee.dataSource.view(); //Issue - this is empty so select (below) will not work

            ddAssignee.select(function (dataItem) {
                return dataItem.AssigneeTypeFK == assigneeTypeFK && dataItem.AssigneeFK == assigneeFK;
            });

        },
        error: function (jqXHR, exception) {
            if (jqXHR.statusText !== 'abort') {
                // Our error logic here
                $('#kNotification').data('kendoNotification').error("An error occurred while loading the page.");
            }
        }
    });
    
}
$('#taskModal').on('click', '#btnSelfAssignTask', function (e) {
 
    //Ajax to return the current user's ID from the controller
    $.ajax({
        url: $(e.currentTarget).data("user-id-url"),
        type: "POST",
        cache: false,
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            var userId = response;

            //Set the value of the dropdown based on the user's id
            var ddAssignee = $('#ddTaskAssignee').data('kendoDropDownList');
            var assigneeDataSource = ddAssignee.dataSource.view(); //For testing
            //TODO improve logic
            ddAssignee.select(function (dataItem) {
                return dataItem.AssigneeTypeFK == 1 && dataItem.AssigneeFK == userId;
            });
        },
        error: function (jqXHR, exception) {
            if (jqXHR.statusText !== 'abort') {
                $('#kNotification').data('kendoNotification').error("An error occurred while assigning task");
            }
        }
    });

});


Georgi Denchev
Telerik team
 answered on 14 Feb 2023
0 answers
132 views
Hi guys,

I want set custom attributes to options in select but I could not find a way to do that. Is there any way to do so?
Ataberk
Top achievements
Rank 1
 asked on 26 Jan 2023
2 answers
4.1K+ views

Hi,

i have a dropdown. When the value is set in open event, the value is selected only for the first 16 items (depending on itemHeight in virtual). How do I get the value to always be selected and automatically scroll to the selected value? Below you'll find a running example.

Thanks for your help.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kendo UI Snippet</title>

    
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.3.1109/styles/kendo.default-ocean-blue.min.css">
    
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2022.3.1109/js/jszip.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2022.3.1109/js/kendo.all.min.js"></script>
</head>
<body>

    <div id="example">
        <div id="grid"></div>
    </div>
    <br>
    <br>
    <br>
  <div id="container">
    <input id="dropdownlist" style="width:300px" />
  </div>


  <script id="templateDDL" type="text/x-kendo-template">
    <span>
      <table>
        <tr class="combo-tr">
            <td class="combo-td">${id}</td>
            <td class="combo-td">${name}</td>
            <td class="combo-td">${description}</td>
        </tr>
    </table>
    </span>
  </script>


<script>
    const maxRecords = 10000;
    let data = [];
    
    class MyData{}  

    function generateData(){
        
        for (let i = 1; i <= maxRecords; i++) {
            let myData = new MyData();

            myData.id = i;
            myData.name = "name" + i;
            myData.description = "description" + i;
            
            data.push(myData);
        }   
    }
    
    generateData();

    $(document).ready(function(){
        $("#grid").kendoGrid({
            dataSource: {
                data: data,
                schema: {
                    model: {
                        fields: {
                            id: {type: "integer"},
                            name: { type: "string" },
                            description: { type: "string" }
                        }
                    }
                },
                pageSize: 25,
                serverPaging: false,
            },
            height: 600,
            sortable: true,
            filterable: true,
            selectable: true,
            pageable: {
                previousNext:   true,    
                numeric:        true,
                buttonCount: 3,
            },
            columns: [
                { field: "id", title: "ID", width: "130px" },    
                { field: "name", title: "Name", width: "130px" },
                { field: "description", title: "Description", width: "130px" }
            ],
            filterable: false,
            scrollable: {
                virtual: false
            },
            change: function(e) {
                        changeDdl();
            },
            dataBound: function(e) {
                this.select("tr:eq(0)");
                this.content.scrollTop(0);
            }
        });

        $("#dropdownlist").kendoDropDownList({
            optionLabel: "-- Please select something --",
            width:300,
            size:"small",
            dataSource: data,
            dataTextField: "name",
            dataValueField: "name",
            template: kendo.template($("#templateDDL").html()), 
            serverPaging: true,
            virtual: {
                itemHeight: 50,
                valueMapper: function(options) {
                    $.ajax({
                        dataSource: data,
                        type: "GET",
                        dataType: "json",
                        data: convertValues(options.value),
                        success: function (data) {
                            options.success(data);
                        }
                    })
                },
            },
            open: function(e){
                const ddl_element = $("#dropdownlist").data("kendoDropDownList");
                // read the current value of ddl (startValue), comes from SetDdlValue
                const startValue = ddl_element.text();
                    
                ddl_element.setDataSource(data);

                // looking for startValue in ddl-dataSource
                const itemEqualToStartValue = ddl_element.dataSource.data().find(x=>x.name === startValue);

                // set value of ddl_element, that is equal to the startValue
                ddl_element.value(itemEqualToStartValue.name);
                ddl_element.trigger("change");
            },
            change: function(e){
            }
        });

        
        // set the DDL value for the first time 
        const grid = $("#grid").data("kendoGrid");
        const selectedItem = grid.dataItem(grid.select());
        
        const ddl_element = $("#dropdownlist").data("kendoDropDownList"); 
        SetDdlValue(ddl_element, selectedItem);
        
        function convertValues(value) {
            let data = {};
            value = $.isArray(value) ? value : [value];
            
            for (let idx = 0; idx < value.length; idx++) {
                data["values[" + idx + "]"] = value[idx];
            }
            return data;
        }
          
        // gets called when change in grid is called
        function changeDdl(){
            const grid = $("#grid").data("kendoGrid");
            const selectedItem = grid.dataItem(grid.select());
            
            const ddl_element = $("#dropdownlist").data("kendoDropDownList"); 
            SetDdlValue(ddl_element, selectedItem);
        }        

        function SetDdlValue(ddl_element, ddl_value) {      
            let TempDDS = [];
            let TempJson = { "id": ddl_value.id, "name": ddl_value.name, "description": ""};
            TempDDS.push(TempJson);
            ddl_element.setDataSource(TempDDS);
            ddl_element.value(ddl_value.name);
            ddl_element.trigger("change");
        }
    });
</script>
</body>
</html>

Neli
Telerik team
 answered on 24 Jan 2023
0 answers
122 views

is it possible to change the behavior to have the item just selected instead of filtered to give the ability to the user to select the value from the whole datasource?

now the user just see limited set of data according to the parent selection

 

Aleksandr
Top achievements
Rank 1
Bronze
Bronze
Veteran
 asked on 17 Dec 2022
1 answer
310 views

I was trying to implement Kendodropdowntree , I came across following situation which I am not able to understand


                $(dropdowntree).kendoDropDownTree({
                placeholder: "Select ...",
                height: "auto",
                dataSource:  //HARD CODED VALUE GOES HERE 
            });
       } 

Above example will work fine when , I hard code those datasource values. When I try to pass some variable there it will not work

var datatobind= somedata // data in exact format it is expected 
{
        
                $(dropdowntree).kendoDropDownTree({
                placeholder: "Select ...",
                height: "auto",
                dataSource:  datatobind
            });
       }

Even I tried passing variable of following type

var dataSourcetype = new kendo.data.HierarchicalDataSource({
        data: datatobind
    });

 
{
        
                $(dropdowntree).kendoDropDownTree({
                placeholder: "Select ...",
                height: "auto",
                dataSource:  dataSourcetype.options.data
            });
       }

But even above also doesn't solve problem, I am not able to get it , why passing exact same variable is not binding to data source.

Lyuboslav
Telerik team
 answered on 14 Dec 2022
1 answer
166 views

Dear team,

I am facing an issue realted to kendo dropdwonlist filter ,we are getting this issue after upgrading to kendo version v2022.2.510 . The issue is after entring the value in serchbox(filter) it is clearing the value automatically by this the calling to the filtering is happening twice to server side. how to prevent this auto clearing please suggest the way. 

 

 

Thank you for your support,

Regards,

Sai

Lyuboslav
Telerik team
 answered on 02 Dec 2022
0 answers
125 views

Hi,

 

I have a DDL that gets its first value from a grid ("myValue"), a simple string that will be written to the DDL (same JSON format that the DDL is expecting

{

field1: "myValue",

field2: ""

}

). When the DDL is opened, the value I entered ("myValue") should be searched in the data source of the DDL and this value should be put into focus. In the end the JSON looks like this:

{

field1: "myValue",

field2: "describtion of myValue"

}

The DDL datasource has to compare the value from field1 ("myValue), if it matches it has to select it,

As long as I don't use virtual this works, but as soon as I use virtual it doesn't work anymore.
How can I achieve that the value from the grid is written into the DDL and the DDL then sets the correct data set into the focus?

Thanks in advance.

Sterling
Top achievements
Rank 2
Iron
 updated question on 30 Nov 2022
1 answer
250 views

Hi,

 

I'm working with an older version of kendo elements. Currently I'm struggling with an tooltip. My Dropdown List shows additional information. However, when the selection changes, the old and new tooltip is displayed. Attached I have three screemshots, additional information (showing the first display of the tooltip), default tooltip (when there is no additional information) and additional information and default tooltip (after the defautl is displayed and a new item is selected). How can I make it to show only the current tooltip?

Here is my code for the tooltip:



$("#myElement").change(function(){
    $("#myElement").kendoTooltip({
         filter: ".k-input",
	 position: "top",
	 showAfter: 500,
	 content: function(e){
	     const dropdownlist = $("#myDdl").data("kendoDropDownList");
	     const selectedItem = dropdownlist.dataItem();
	     if (selectedItem.field2 === undefined) {
	         selectedItem.field2 = "This is the default tooltip";
	     }
	     const result = $("<div style='text-align: center';></div>").text(selectedItem.field2).css("width", 
                            (selectedItem.field2.length * .6) + "em");
	     return result;
         }
    }).data("kendoTooltip");
});


Neli
Telerik team
 answered on 11 Nov 2022
1 answer
115 views

I have a combobox that gets populated with a datasource.  How can I disable a single item in the combobox based on the value of a different form field?  For example, the combobox has 5 items, A, B, C, D, and E and they are all active.  There is a form field called letterDoc and if letterDoc has a value of 8, I want to disable item A.

 

Is this possible?

 

Thank you.

 

Lyuboslav
Telerik team
 answered on 09 Nov 2022
1 answer
276 views

I have a block of html that I want to move from one div to another div on the page using javascript. I am writing a function that will move this code block and will have no idea if, or how many, dropdown lists exist as it will be different every time. My problem is that when I do a .clone(true, true) with JQuery, the dropdownlist either stops opening or it opens with a width of 0 in the upper left corner of the screen. How do I fix this?

Task: Move everything from block1 to block2. 

<div id="block1">
<p>Hi! I'm a paragraph.</p>
<select id="select1"></select>
The select was already initialized with JS and works fine.
</div>

<div id="block2">

</div>

Martin
Telerik team
 answered on 06 Oct 2022
Narrow your results
Selected tags
Tags
Grid
General Discussions
Charts
Data Source
Scheduler
TreeView
MVVM
Editor
Window
Date/Time Pickers
Spreadsheet
Upload
ListView (Mobile)
ComboBox
TabStrip
MultiSelect
AutoComplete
ListView
Menu
Templates
Gantt
Validation
TreeList
Diagram
NumericTextBox
Splitter
PanelBar
Application
Map
Drag and Drop
ToolTip
Calendar
PivotGrid
ScrollView (Mobile)
Toolbar
TabStrip (Mobile)
Slider
Button (Mobile)
SPA
Filter
Drawer (Mobile)
Drawing API
Globalization
Gauges
Sortable
ModalView
Hierarchical Data Source
Button
FileManager
MaskedTextBox
View
Form
NavBar
Notification
Switch (Mobile)
SplitView
ListBox
DropDownTree
PDFViewer
Sparkline
ActionSheet
TileLayout
PopOver (Mobile)
TreeMap
ButtonGroup
ColorPicker
Pager
Styling
MultiColumnComboBox
Chat
DateRangePicker
Dialog
Checkbox
Timeline
Drawer
DateInput
ProgressBar
MediaPlayer
ImageEditor
OrgChart
TextBox
Effects
Accessibility
ScrollView
PivotGridV2
BulletChart
Licensing
QRCode
ResponsivePanel
Switch
Wizard
CheckBoxGroup
TextArea
Barcode
Collapsible
Localization
MultiViewCalendar
Touch
Breadcrumb
RadioButton
Stepper
Card
ExpansionPanel
Rating
RadioGroup
Badge
Captcha
Heatmap
AppBar
Loader
Security
Popover
DockManager
FloatingActionButton
TaskBoard
CircularGauge
ColorGradient
ColorPalette
DropDownButton
TimeDurationPicker
ToggleButton
BottomNavigation
Ripple
SkeletonContainer
Avatar
Circular ProgressBar
FlatColorPicker
SplitButton
Signature
Chip
ChipList
VS Code Extension
AIPrompt
PropertyGrid
Sankey
Chart Wizard
OTP Input
SpeechToTextButton
InlineAIPrompt
+139 more
Top users last month
Jay
Top achievements
Rank 3
Iron
Iron
Iron
Benjamin
Top achievements
Rank 3
Bronze
Iron
Veteran
Radek
Top achievements
Rank 2
Iron
Iron
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Richard
Top achievements
Rank 4
Bronze
Bronze
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Iron
Iron
Iron
Benjamin
Top achievements
Rank 3
Bronze
Iron
Veteran
Radek
Top achievements
Rank 2
Iron
Iron
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Richard
Top achievements
Rank 4
Bronze
Bronze
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?