Select TypeError ui.item undefined Jquery Autocomplete - javascript

here is my autocomplete select code:
$('.js-main-search').autocomplete({
minLength: 3,
source: function(request, response) {
$.getJSON('/dashboard/searchDocumentsAndCompanies.do',
{ q: request.term},
function(data) {
if(data.length == 0){
data = [
{name: 'No matches found', resultType: 'COMPANY', noResults: true},
{name: 'No matches found', resultType: 'BRANCHES', noResults: true}
];
}
data.unshift({name: 'Search from documents »',resultType: 'DOCUMENT', reqQuery: request.term});
response(data);
});
},
select: function(event, ul) {
event.preventDefault();
selected = true;
if (ul.item.resultType == 'DOCUMENT' && !wasSearched) {
wasSearched = true;
$(".textbox.ui-front li:eq(1)").before('<li class="search-category ui-menu-item">Documents</li>');
$.getJSON(Telema.CONTEXT_PATH + '/dashboard/searchDocumentsAndCompanies.do',
{q: ul.item.reqQuery, resultType: ul.item.resultType},
function (data) {
if (data.length == 0) {
data = [
{name: 'No matches found', resultType: 'DOCUMENT', noResults: true}
];
}
$.each(data, function (index, document) {
$(".textbox.ui-front li:eq(1)").after('<li class="ui-menu-item">' + document.name + '</li>');
});
});
}
}
});
Html:
<div class="search">
<form id="searchForm" action="/">
<div class="search-form cfx">
<input id="topSearchButton" type="submit" class="btn" value="">
<div class="textbox ui-front">
<input id="topSearchInput" type="text" class="textbox-input js-main-search ui-autocomplete-input" autocomplete="off">
<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" tabindex="0" style="display: none;"></ul></div>
</div>
</form>
</div>
I have TypeError ul.item undefined when I click one of the menu items. Could anyone suggest on that. If any more information is needed, I'd be happy to supply it!

Per the jQuery UI docs, the ui parameter to the select event handler has a property called item, which is an object with -- by default -- two properties: a label and a value. If you need an additional resultType property, you must explicitly define it as part of the source property when you initialize the autocomplete widget. Something like this:
source: (request, response) ->
$.get .............
response $.map data, (request_data) ->
{
label: request_data.value.replace(regex, "<strong>$1</strong>"),
value: if request_data.id == "" then $('#q').val() else request_data.value,
id: request_data.id
resultType: request_data.resulttype
}
Source: http://www.codedisqus.com/0mNVUVekWW/jquery-autocomplete-select-ignores-custom-data-fields.html

Related

Why kendo.observable do not read datasource

Could you explain why kendo ui observable do not read data source when bind to html ?
I based my code on this example : http://demos.telerik.com/kendo-ui/mvvm/remote-binding
I don't understand the link between the dropdown and the observable.
InitObservable = function (Id) {
viewModel = kendo.observable({
//create a dataSource
tacheDataSource: new kendo.data.DataSource({
autoSync: true,
transport: {
read: {
url: function () {
return crudServiceBaseUrl + "/Taches?ID=" + Id;
},
method: "GET",
dataType: "json"
}
,
update: {
url: crudServiceBaseUrl + "/Taches",
method: "PATCH",
dataType: "json"
}
,
destroy: {
url: crudServiceBaseUrl + "/Taches/Destroy",
dataType: "json"
}
,
create: {
url: crudServiceBaseUrl + "/Taches",
method: "POST",
dataType: "json"
}
,
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ID",
fields: TacheFields
}
}
}), // endDatasource
selectedTache: null, //this field will contain the edited dataItem
hasChange: false,
save: function (e) {
this.tacheDataSource.sync();
this.set("hasChange", false);
},
remove: function () {
if (confirm("Etes vous sûr(e) de vouloir supprimer cette tâche ?")) {
this.tacheDataSource.remove(this.selectedTache);
this.set("selectedTache", this.tacheDataSource.view()[0]);
this.change();
}
},
showForm: function () {
return this.get("selectedTache") !== null;
},
change: function () {
this.set("hasChanges", true);
}//,
//cancel: function () {
// this.dataSource.cancelChanges(); //calcel all the change
// validator.hideMessages(); //hide the warning messages
// $("#tacheWindow").data("kendoWindow").close();
//}
});
kendo.bind($("#tacheWindow"), viewModel);
}
I tested the datasource alone with datasource.read(), it works.
What is the trigger of the read of the datasource ?
----- New details
I added
type: "odata-v4"
in the datasource and I updated the schema as this :
e
schema: {
data:function(data){
var toReturn = data.value;
return toReturn;
},
model: {
id: "ID",
fields: TacheFields
}
}
And this to force read()
viewModel.selectedTache = proprietesEcranTache.tacheId;
if (viewModel.showForm()) {
viewModel.tacheDataSource.read();
kendo.bind($("#tacheWindow"), viewModel);
}
I see my answer in network debugger of chrome and I know I receive data in the form witout error but no data are displayed.
Here the oData answer
{
"#odata.context":"http://localhost:14986/odata/$metadata#Taches","value":
[
{
"ID":1,"Description":"D\u00e9marrage application","CreateurId":7,"TypeTacheID":1,"EtatTacheID":6,"ValidantId":null,"DateValidation":null,"EstValidee":false,"CommentaireValidation":null,"EvennementPrecedentID":null
}
]
}
Here is my form
<div id="tacheWindow">
<form id="TacheForm">
<ul class="TacheFormFields">
<li class="">
<div class="formFieldTitle">Id</div>
<div class="formFieldInput textField"><input id="tacheId" type="text" data-bind="value: ID" /></div>
</li>
<li>
<div class="formFieldTitle">Type de tâche</div>
<select id="typesTachesDdl" data-role="dropdownlist"
data-bind="value: TypeTacheID"
data-value-primitive="true"
data-text-field="Nom"
data-value-field="ID"></select>
</li>
<li>
<div class="formFieldTitle">Description</div>
<div class="formFieldInput textField">
<input type="text" data-bind="value: Description" />
</div>
</li>
<li>
<div class="formFieldTitle">Createur</div>
<select id="CreateursDdl" data-role="dropdownlist"
data-bind="value: CreateurId"
data-value-primitive="true"
data-text-field="Nom"
data-value-field="ID"></select>
</li>
<li>
<div class="formFieldTitle">Validant</div>
<select id="ValidantsDdl" data-role="dropdownlist"
data-bind="value: ValidantId"
data-value-primitive="true"
data-text-field="Nom"
data-value-field="ID"
disabled="disabled"></select>
</li>
</ul>
<div class="dialog_buttons">
<button id="TacheFormTemplateSave" data-bind="click: observableSave" class="k-button">Ok</button>
<button id="TacheFormTemplateSave" data-bind="click: observableCancel" class="k-button">Annuler</button>
</div>
</form>
Placing the datasource within your view model simply makes it observable and nothing more, as you have noted. It will only get read when passed to a kendo widget (such as a DropDownList). The telerik demo shows this within the bound html container:
<select data-role="dropdownlist" data-option-label="Select product"
data-value-field="ProductID" data-text-field="ProductName"
data-bind="source: productsSource, value: selectedProduct" style="width: 100%;"></select>
The kendo.bind statement scans the html container for elements with a data-role attribute. In the case above it will find data-role="dropdownlist", instantiate a DropDownList widget and add the necessary html elements for it to the DOM. This part of the declaration:
data-bind="source: productsSource"
...will search for a datasource named 'productsSource' within the view model and assign it to the DropDownList as its datasource to use. The DropDownList will then trigger a read of that datasource in order to populate itself with data.
I created a simple sample that works
Home Page
<div id="editForm">
<table>
<tr>
<td>Id</td>
<td>Nom</td>
</tr>
<tr>
<td>
<input data-role="dropdownlist"
data-auto-bind="false"
data-text-field="Nom"
data-value-field="ID"
data-bind="value: selectedPerson,
source: persons,
visible: isVisible,
enabled: isEnabled,
events: {
change: onChange
}"
style="width: 200px;" />
</td>
<td><input type="text" data-value-update="displaySelectedPerson" data-bind="value: selectedPerson.Nom" class="k-textbox" /></td>
</tr>
</table>
</div>
Important detail : in the text box : data-bind="value: selectedPerson.Nom"
This allow observable to update the field.
Javascript :
var persons = [
{ ID: "1", Nom: "Lolo" },
{ ID: "2", Nom: "Toto" }
];
documentReady = function () {
var viewModel = new kendo.observable({
personsSource: persons
, persons: new kendo.data.DataSource({
data: persons,
schema: {
model: {
fields: {
ID: { type: "number" }
, Nom: { type: "string" }
}
}
}
})
, selectedPerson: null
, hasChange : false
, isPrimitive: false
, isVisible: true
, isEnabled: true
, primitiveChanged: function () {
this.set("selectedPerson", null);
}
, onChange: function () {
console.log("event :: change (" + this.displaySelectedPerson() + ")");
}
, displaySelectedPerson: function () {
var selectedPerson = this.get("selectedPerson");
return kendo.stringify(selectedPerson, null, 4);
}
});
kendo.bind($("#editForm"), viewModel);
}

Play Framework: cannot read value of textfield with javascript

I could not figure out a way to read the current value of the email field. Everytime I read it, for example with a keyup event, nothing is retrieved. This issue just affects this field. I can read the values of the other textfields without a problem.
createFormOnly.scala.html
This is my view containing the form and jquery code to print the value of the text field. Note that the validation of the #fullname field works without any troubles.
#(signupForm: Form[models.Register], loginForm: Form[Application.Login])
#import helper._
#implicitFieldConstructor = #{
FieldConstructor(twitterBootstrapInput.render)
}
<div class="well">
<h3>#Messages("signup.new")</h3>
#if(flash.get("error")!=null) {
<p class="error">
<span class="label label-danger">#Messages(flash.get("error"))</span>
</p>
}
#form(controllers.account.routes.Signup.save(), 'id -> "signupForm") {
<script type="text/javascript">
$( document ).ready(
function()
{
// Setup form validation on the signupForm element
$("#signupForm").validate({
// Specify the validation rules
rules: {
email: {
required: true
},
fullname: {
required: true,
namecheck: true
}
},
// Specify the validation error messages
messages: {
email: "<p class='error'><span class='label label-danger'>Email missing.</span></p>",
fullname: "<p class='error'><span class='label label-danger'>Name is already used.</span></p>"
},
// handler which handles the submit
submitHandler: function(form) {
form.submit();
}
});
jQuery.validator.addMethod("namecheck", function(value) {
var dataString = {
"action" : "namecheck",
"display_name" : value
};
var check_result = false;
jQuery.ajax({
type: "GET",
url: "http://localhost:9000/checkName/"+$( '#fullname' ).val(),
async: false,
data: dataString,
dataType: "json",
success: function(data){
check_result = (data.toString() == "true");
}
});
console.log(check_result);
return check_result;
}, "error message");
$('body').on("keyup",'#email', function(){
console.log('keyed email');
console.log($('body #email').val());
console.log($('#email').val());
console.log($('#email').attr('value'));
});
$('body').on("keyup",'#fullname', function(){
console.log('keyed fullname');
console.log($('body #fullname').val());
console.log($('#fullname').val());
console.log($('#fullname').attr('value'));
});
}
);
</script>
<ul class="list-group">
<li class="list-group-item">
#inputText(
signupForm("email"),
'placeholder -> Messages("accout.register.create.email"),
'_label -> Messages("email"),
'class -> "form-control",
'_showConstraints -> false,
'id -> "email"
)
</li>
<li class="list-group-item">
#inputText(
signupForm("fullname"),
'placeholder -> Messages("accout.register.create.fullname"),
'_label -> Messages("fullname"),
'class -> "form-control",
'_showConstraints -> false,
'id -> "fullname"
)
</li>
<li class="list-group-item">
#inputPassword(
signupForm("inputPassword"),
'_label -> Messages("password"),
'placeholder -> Messages("accout.register.create.password"),
'class -> "form-control",
'_showConstraints -> false
)
</li>
<li class="list-group-item">
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="#Messages("signup.signup")">
</div>
</li>
</ul>
}
</div>
View creating the form create.scala.html
#(signupForm: Form[models.Register], loginForm: Form[Application.Login])
#scripts = {
<script src="#routes.Assets.at("javascripts/password.js")" type="text/javascript"></script>
}
#main(null, scripts) {
#views.html.guestNavBar(loginForm)
#createFormOnly(signupForm, loginForm)
}
Running it in Chrome / Console output
Now i run the application an type values in the the text fields. An 'a' in the fullname textfield and an 'e' into the email textfield. As shown in the console it is empty.
keyed fullname signup:234
a signup:235
a signup:236
signup:237
true signup:222
keyed email signup:77
signup:78
signup:79
signup:80
A clue might be in the jQuery documentation for the 'val()' mathod:
"Get the current value of the first element in the set of matched elements"
So where you have:
console.log($('#email').val());
It could be in fact another element other than your input that's getting its value output.
Check the HTML that gets output to the browser for another element with ID 'email'. 'email' being quite a generic name there might be something else in the page using this ID.

Select2 (input) value as object after select item

I have a select2 (jQuery plugin) on my code which works normally except for the case when I select an item.
The value is wrong.
Form:
<form id="Teste" method="get" action="">
<input type="hidden" id="e6" name="e6" class="select2" style="width: 600px;" />
<input type="submit" value="Send" />
</form>
Input from select2 - hidden (required for remote data) - value: [Object]:
<input type="hidden" id="e6" name="e6" class="select2 select2-offscreen" style="width: 600px;" tabindex="-1" title="" value="[object Object]">
Javascript used for instance select2:
function formatRes(item) {
return item.Text;
}
function formatSel(item) {
return item.Value;
}
$("#e6").select2({
placeholder: "Select your supplier",
minimumInputLength: 0,
id: function(data){return {id: data.id};},
allowClear: true,
ajax: {
url: "http://localhost:1396/List/_GetDropDownListSupplier",
dataType: 'jsonp',
quietMillis: 300,
data: function (term, page) {
return {
searchString: term,
pageSize: 60,
pageIndex: page,
};
},
results: function (data, page) {
return {results: data.results, more: (page * 60) < data.total };
}
},
formatResult: formatRes,
formatSelection: formatSel,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Json example returned by ajax to Select2:
{"results":[{"Selected":false,"Text":"Cezar Barbara","Value":"724"},{"Selected":false,"Text":"Cezar Barbara","Value":"765"}],"total":82}
Solved:
id: function(data){return data.Value;}
I was returning a object with id and not a directly value.
Thanks to #mgibsonbr from Stackoverflow PT
You need to use a select element, try this:
<form>
...
<select id="someSelect">
//options
</select>
<input type="hidden" name="fromSelect" id="fromSelect" value=""/>
</form>
You have two options here:
1.- Get the value direct from select:
var selected = $('#someSelect').val();
2.- Assign the value to the hidden input and then get its value:
$('#someSelect').on('change', function(){
$('#fromSelect').attr('value', this.value);
});
var selected = $('#fromSelect').val();

In jquery autocomplete, how to disply label and submit the id corresponding to label

I have a search field which use jquery autocomplete.In this textbox that drops down a list of employee names suggested by the autocomplete.But when my form is submitted I don't want the persons name sent along with form, I want the employee id sent with the form.How I can do that?
<input id="employee">
<input type="hidden" id="employee_id">
Above given is the textfield I used
$(function () {
$.ajax({
url: '/accounts/allEmp',
type: "get",
cache: false,
success: function (data) {
var arr = [];
arr = data.employee;
$("#employee").autocomplete({
minLength: 0,
source: arr,
focus: function (event, ui) {
$("#employee").val(ui.item.name);
return false;
},
select: function (event, ui) {
$("#employee").val(ui.item.name);
$("#employee_id").val(ui.item.id);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name)
.appendTo(ul);
};
}
});
});
This is the script I used.While I entering characters in the textfield it doesn't show any results but when remove those characters from textfield it will show all the entities(sorting is not working).And the array look like
array="employee":
[ { "name": "a", "id": 1 },
{ "name": "b", "id": 2 },
{ "name": "c", "id": 3 } ]
Please help me.Thanks in advance.
Do you control server side of source url? If so I suggest you use "value" property name instead of "name" as described in autocomplete api.
Otherwise you can modify that array in place and add "value" properties on the fly.
Here is fiddle I just created from your snippet. With click on "send" it crashes I don't know why but if you look in your developer's panel network request is getting through with params:
employee[name]:Fred
employee[id]:first
DEMO
JS code:
var data = {
json: "{\"employee\":[{\"value\":\"A\",\"id\":\"1\"},{\"value\":\"B\",\"id\":\"2\"},{\"value\":\"C\",\"id\":\"3\"}]}"
}
$(function () {
$('#submit').click(function(){
alert('Employee name = '+$('#employee_name').val()+' Employee id = '+$('#employee_id').val());
});
$.ajax({
url:"/echo/json/",
data: data,
type: "POST",
success:function(data) {
console.log(data);
var arr = data.employee;
$("#employee_name").autocomplete({
minLength: 0,
source: arr,
select: function (event, ui) {
$("#employee_name").val(ui.item.value);
$("#employee_id").val(ui.item.id);
return false;
}
});
}
});
});
HTML code:
<form>
Employee name (Type like "A" or "B" or "C")<br>
<input id="employee_name" name="employee_name">
<br>
Selected Employee id (hidden field):
<input type="text" id="employee_id" name="employee_id" readonly>
<br>
<input type="button" value="Submit" name="submit" id="submit" onclick="check_fields()">

I want to filter in the list if the text box value is changed using knockout

I want to filter in the list if the text box value is changed if the
JSON Returned in Ajax call is as I am using two different model.
Filteration should show hide or just filter the data I am providing you the JSON data what I am getting from the ajax call. Thanks
Data = [{"code":"Grand Financial","cls":"Branch","Chk":true},{"code":"Joan Group","cls":"Branch","Chk":true}]
var searchModel, advisorGroupModel;
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/ASPNET/Reports/GetAdvisorGroups',
dataType: "json",
success: function (data) {
advisorGroupModel = {
advisorGroup: ko.observableArray(data)
};
ko.applyBindings(advisorGroupModel, document.getElementById("advisorGroupModel"));
}
})
var searchModel = {
searchQuery: ko.observable('')
};
searchModel.searchHandle= ko.dependentObservable(function () {
var code = this.searchQuery().toLowerCase();
return ko.utils.arrayFilter(advisorGroupModel, function (beer) {
debugger;
return beer.code.toLowerCase().indexOf(code) >= 0;
});
console.log(search);
}, searchModel)
ko.applyBindings(searchModel, document.getElementById("searchModel"));
});
<div id="searchModel">
<input data-bind="value: searchQuery, valueUpdate: 'keyup'" />
<h6 data-bind="text: searchQuery"></h6>
</div>
<div class="CheckBoxListGroup" id="advisorGroupModel">
<ul data-bind="template: { name: 'advisorGroupTemplate', foreach: advisorGroup, as: 'singleAdvisorGroup' }"></ul>
<script type="text/html" id="advisorGroupTemplate">
<li>
<input type="checkbox" data-bind="attr: { value: code, id: code, checked: Chk }" name="GroupsSel">
<label data-bind="attr: { for: code }, text: '' + code + ' (' + cls + ')' "></label>
</li>
</script>
</div>
don't bind your display to the entire list, bind your display to a computed function that returns the filtered list or returns all items when there are no filters.
then on your keyup call your filterlist function that filters the list removing the ones that do not match your filter

Categories

Resources