Get kendo dropdownlist value/text/index in selected kendo grid mvvm

Hendra picture Hendra · May 21, 2014 · Viewed 17.3k times · Source

I'm able to add a kendo dropdownlist into kendo grid by template scenario below:

<script type="text/x-kendo-template" id="ddlGrid">
    <input data-role="dropdownlist"
       data-text-field="Text"
       data-value-field="Value"
       data-bind="source: actionSource, events: { change: onChange}"/>
</script>
<div class="demo-section">
<div class="k-content" style="width: 100%">
    <div id="grid"
         data-role="grid"
         data-sortable="true"
         data-selectable="true"
         data-columns="[
            { field: 'ProductID' },
            { field: 'ProductName' },
            { field: 'UnitPrice' },
            { field: 'UnitsInStock' },
            { field: 'Discontinued' },
            { title: 'Action', template: kendo.template($('#ddlGrid').html())} ]"
         data-bind="source: dataSource, event">
    </div>
</div>

However, the problem is how to access that dropdownlist to get it value/text/index. So far I can get the selected row data using this approach:

var onClick = function (event, delegate) {
  event.preventDefault();
  var grid = $("#grid").data("kendoGrid");
  var selectedRow = grid.select();
  var dataItem = grid.dataItem(selectedRow);
  if (selectedRow.length > 0)
    delegate(dataItem);
  else
    alert("Please select a row.");
  };

var viewModel = new kendo.data.ObservableObject({
    dataSource: productDatasource,
    actionSource: actionDataSource,

    onChange: function (event) {
        onClick(event, function (dataItem) {
            alert(dataItem.ProductID + " " + dataItem.ProductName);
        });            
    },

});

Here is the JSFiddle code

Please help me, I'm stuck.

Thanks in advance.

Answer

OnaBai picture OnaBai · May 21, 2014

You can access DropDownList text and value using:

var value = event.sender.value();
var text = event.sender.text();

inside your onChange function:

onChange: function (event) {
    alert ("Text/Value : " + event.sender.text() + "/" + event.sender.value());
    onClick(event, function (dataItem) {
        alert(dataItem.ProductID + " " + dataItem.ProductName);
    });            
},

BUT I'm actually not sure why are you defining onClick and all that complex code when you can get the dataItem simply doing:

var viewModel = new kendo.data.ObservableObject({
    dataSource: productDatasource,
    actionSource: actionDataSource,

    onChange: function (event) {
        alert ("Text/Value : " + event.sender.text() + "/" + event.sender.value());
        var grid = $("#grid").data("kendoGrid");
        var dataItem = grid.dataItem($(event.sender.wrapper).closest("tr"));
        alert(dataItem.ProductID + " " + dataItem.ProductName);
    },

});
kendo.bind($("#grid"), viewModel);

See it here : http://jsfiddle.net/OnaBai/hLG98/12/