This is a migrated thread and some comments may be shown as answers.

AutoComplete event handler is not defined

1 Answer 32 Views
AutoComplete
This is a migrated thread and some comments may be shown as answers.
Allen
Top achievements
Rank 1
Veteran
Allen asked on 21 Apr 2021, 08:25 PM

The code below is within a poup editor when user click the EDIT button in a row of a grid.

I want to handle when autocomplete field changed.

I added .Events(e => e.Change("autocomplete_change")) in the wrapper and add a javascipt function autocomplete_change() after the wrapper 

when run it and click one of the edit button in a grid row, I got autocomplete_change is not defined error and  the popup will show under the grid without any data.

Is there anyone could help me to let me know how to fix it and  what's going on.

thank you very much.

@(Html.Kendo().AutoCompleteFor(model => model.AnswerA)
                .Name("AnswerA")
                .DataTextField("Answer")
                .Placeholder("Type a answer")
                .Filter("Contains")
                .MinLength(5)
                .HtmlAttributes(new { style = "width:100%" })
                .Height(520)
                .Events(e => e.Change("autocomplete_change"))
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("ResponseRead", "Method")
                            .Data("onAnswerAData");
                    })
                    .ServerFiltering(true);
                })
              
            )
            <script>
                 function autocomplete_change() {
                       alter("call ShowAddingAnswerPrompt");
                    }
            </script>

1 Answer, 1 is accepted

Sort by
0
Ivan Danchev
Telerik team
answered on 26 Apr 2021, 03:27 PM

Hello Allen,

In scenarios that involve partial views, as in this case where a popup editor  is used, the event handlers should be placed before the initialization of the respective component. Try moving the script block with the handler:

 <script>
      function autocomplete_change() {
           alter("call ShowAddingAnswerPrompt");
      }
 </script>

before the initialization of the AutoComplete.

This should fix the error with the handler not being defined.

Regards,
Ivan Danchev
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Allen
Top achievements
Rank 1
Veteran
commented on 26 Apr 2021, 10:20 PM

Thanks Ivan,

Before you replied me, I found I can use what I want is here https://www.telerik.com/forums/add-a-button-in-nodatatemplate-of-autocomplete-in-mvc-3b326ce27b97.

In this post, you mentioned that it could use NoDataTemplateId to allow user add a text which is not existed.

After it worked to allow user input new text, I still don't have a way to save it

I use serverside, so when user want to add a new text, I need to insert a record into database. May I know where to put code to save the data?

Below are what I have tried.

1. add .Create(update => update.Action("ResponseInsert", "Method").Type(HttpVerbs.Post)) in the DataSource block, but not sure how to put the text as a parameter

@(Html.Kendo().AutoCompleteFor(model => model.AnswerA)
                .Name("AnswerA")
                .DataTextField("Answer")
                .Placeholder("Type a answer")
                .Filter("Contains")
                .MinLength(5)
                .HtmlAttributes(new { style = "width:100%" })
                .NoDataTemplateId("noAnswerTemplate")
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("ResponseRead", "Method")
                            .Data("onAnswerAData");

                    })
                  
                    .ServerFiltering(true);
                })
              
            )

 

2. try to add ajax call inside the confirm block belowm but it seems I can not add ajax inside it.

function addNewAnswer(widgetId, value) {
             var widget = $("#" + widgetId).getKendoAutoComplete();
             var dataSource = widget.dataSource;

             if (confirm("Please confirm you want to add this answer?")) {

                 dataSource.add({
                     Value: 0,
                     Text: value
                 });

                 dataSource.one("sync", function () {
                     widget.close();
                 });

                 dataSource.sync();
             }
             else {
                 $("#" + widgetId).val("");
             }

         }
        </script>
        <script id="noAnswerTemplate" type="text/x-kendo-tmpl">
            <div class="message">
            The answer you input  - '#: instance.element.val() #' - is not existing in Database.
            </div>
            <br />
            <button class="k-button k-primary" onclick="addNewAnswer('#: instance.element[0].id #', '#: instance.element.val() #')">Add a New Answer</button>
        </script>

 

Ivan Danchev
Telerik team
commented on 29 Apr 2021, 03:44 PM

Allen,

Achieving sending the new item's text to the server requires setting up a create transport operation in the dataSource of the AutoComplete. Here's an example:

@(Html.Kendo().AutoComplete()
	.Name("AnswerA")
	.DataTextField("ProductName")
	.NoDataTemplateId("noAnswerTemplate")
)

<script id="noAnswerTemplate" type="text/x-kendo-tmpl">
	<div class="message">
	The answer you input  - '#: instance.element.val() #' - is not existing in Database.
	</div>
	<br />
	<button class="k-button k-primary" onclick="addNewAnswer('#: instance.element[0].id #', '#: instance.element.val() #')">Add a New Answer</button>
</script>

<script>
	function addNewAnswer(widgetId, value) {
		var widget = $("#" + widgetId).getKendoAutoComplete();
		var dataSource = widget.dataSource;

		if (confirm("Are you sure?")) {
			dataSource.add({
				ProductID: 0,
				ProductName: value
			});

			dataSource.sync();
		}
	}
</script>

<script>
	$(document).ready(function () {
		var dataSource = new kendo.data.DataSource({
			batch: true,
			transport: {
				read: {
					url: "/Home/Read",
					dataType: "json"
				},
				create: {
					url: "/Home/Create",
					dataType: "json"
				},
				parameterMap: function (options, operation) {
					if (operation !== "read" && options.models) {
						return {
							productID: options.models[0].ProductID,
							productName: options.models[0].ProductName
						};
					}
				}
			},
			schema: {
				model: {
					id: "ProductID",
					fields: {
						ProductID: { type: "number" },
						ProductName: { type: "string" }
					}
				}
			}
		});

		$("#AnswerA").data("kendoAutoComplete").setDataSource(dataSource);

	});
</script>

Note that:
1. The dataSource is created on document.ready and is set to the AutoComplete with the setDataSource method.
2. The create operation calls the Create action in the Home controller.
3. Data is passed to the action using the parameterMap functions. It returns two parameters (productID and productName).
4. The action should expect parameters with the same names:

public ActionResult Create(string productID, string productName)

I am using the ProductID and ProductName in the data, so in your case you should use your own fields and replace mine where needed.

Regards,
Ivan Danchev
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
AutoComplete
Asked by
Allen
Top achievements
Rank 1
Veteran
Answers by
Ivan Danchev
Telerik team
Share this question
or