Need Value Already Set
I am using Kendo autocomplete to select an item from a list. I need to set the value of the text input field and make that actually use the value from the list.
Right now I am setting the text value of the input field to the value of the item in the table, though it is not actually using it as though you were to type it in and click on the auto-completed item.
Setting the default text :
IQueryable<StorageLocation> query = (from s in db.StorageLocations.Include("StorageLocationType") select s);
DefaultStorageLocation = query.Count() != 1 ? "" : query.FirstOrDefault().TitleWithType;
Setting the value of the text box:
<input type="text" value="<%: Model.DefaultStorageLocation %>" name="StorageLocation" id="StorageLocation" originalname="StorageLocation" placeholder="" class="autoComplete" style="width: 158px;" />
My Kendo AutoComplete:
$('#StorageLocation' + rowID).kendoAutoComplete({
dataTextField: 'title',
dataValueField: 'id',
minLength: 2,
autoBind: false,
select: function (e) {
var dataItem = this.dataItem(e.item.index());
$('#StorageLocationID' + rowID).val(dataItem.id);
},
dataSource: {
type: 'json',
serverFiltering: true,
transport: {
read: {
url: function (opt) {
return '/Autocomplete/StorageLocations?searchText=' + opt.filter.filters[0].value;
}
}
}
}
});
So in short.
I am setting the value of the text input
Need it to actually use the value as if it were selected from autocomplete
It looks like you're trying to auto-select the first value when there is only one. I think the suggest property will do what you're looking for: http://docs.telerik.com/kendo-ui/api/javascript/ui/autocomplete#configuration-suggest
Alternatively, try the value method: http://docs.telerik.com/kendo-ui/api/javascript/ui/autocomplete#methods-value
Controller searchResult search query
storageLocation = (DefaultWarehouseForIA && !StorageLocation.IsNull()) ? StorageLocation.TitleWithType : "",
defaultStorageLocationID = (DefaultWarehouseForIA && DefaultStorageLocationID.ToLong() > 0) ? DefaultStorageLocationID : null
JS values being filled when another text field is filled in.
select: function (e) {
var dataItem = this.dataItem(e.item.index());
$('#StorageLocation' + rowID).val(dataItem.storageLocation);
$('#StorageLocationID' + rowID).val(dataItem.defaultStorageLocationID);
}
At this point I have figured it out. Have it working.
So now the value is being auto filled when another text field is being filled in.
Explanation isn't too great here. But hey.
Related
I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}
change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events
I built an autocomplete list of cities using a mysql query. Typing in the input field correctly initiates the search and builds the selectable city list. The problem is that the city name in full does not get saved, only the characters typed when using .on('change'... I tried other mouse events such as mouseover, mousemove, mouseout, mouseenter, mouseleave - and they require the user to first select the item from the list, move out, then swipe the cursor over the input a second time to actually trigger the save of the selected city name. The html looks like:
<input type="text" onmouseover="this.focus();" class="saveCity" name="pob_city" member_id="<?php echo $member_id; ?>" value="<?php echo $pob_city; ?>" placeholder="City" id="pob_city" />
<script language="javascript" type="text/javascript"> $("#pob_city").coolautosuggest({ url:"tools/autosuggest/query_cities.php?chars=" }); </script>
The saveCityCountry javascript:
$(document).on('mouseout','.saveCity',function()
{
var DATA=$(this).val();
var n =remove_whitespaces(DATA);
var MEMBER_ID=$(this).attr('member_id');
$("#Results").html( "" );
if(n !=''){
var dataString = 'pob_city='+ n +'&member_id='+MEMBER_ID;
$.ajax({
type: "POST",
url: "saveData.php",
data: dataString,
cache: false,
success: function(html)
{
$("#Results").html( html );
}
});
}
})
You can see a demo at: http://dottedi.us/misc/ajaxsave/
The other thing that is slightly bothersome is that with ordinary input fields such as first or last name, the on change event only triggers when you click somewhere else on the page, thus the placebo "Save" button.
Update: I cleaned up the code in my example splitting off City from Country and updated the post to reference saveCity. This will not affect the result, just a bit easier to follow.
Inside the http://dottedi.us/misc/ajaxsave/tools/autosuggest/js/ folder are two javascript files that might be relevant, jquery.coolautosuggest.js and jquery.coolfieldset.js. On line 46 of jquery.coolautosuggest.js I see success:function(data){. You want me to place "source: data, autoFocus: true, delay: 0, minLength: 0, select: response, response: response" somewhere in here? Please make it clear where and with the right syntax, semicolin, etc.
In the codeblock you added, I assume that I change the HTML adding the ,response and the function response just gets placed somewhere within my saveData.js. Once this is right, do I go back to change as opposed to mouseout or mouseover?
include response function in your autocomplete call, where you can assign the selected value to hidden field, This will allow you to retain full text.
I assume you are getting array of cities, store each city in an array in a key called "city" and return it.
Define one hidden field say "selected_city".
Inside your coolautosuggest success function place this code
source: data,
autoFocus: true,
delay: 0,
minLength: 0,
select: response,
response: response
$("#pob_city").coolautosuggest({ url:"tools/autosuggest/query_cities.php?chars=" },response);
function response(){
if (typeof ui.content != "undefined" && ui.content.length === 1) {
city= ui.content[0].city;
}
else if (typeof ui.item != "undefined" && ui.item.label.length > 0) {
city= ui.item.label;
}
if (label.length > 0 || index.length > 0) {
$("#selected_city").val(city);
// this value you can use to display
}
}
before doing this please change the below function on jquery.coolautosuggest.js at line 120
if(me.submitOnSelect==true){ $("form").has(me.textField).submit();
}
to
if(me.submitOnSelect==true){
$("#pob_city").val($(this).find(".suggestion_title").text()); $("form").has(me.textField).submit();
}
I am creating a drop down dynamically after an ajax all and populating the fields. I am also calling jquery.data() to set some attribute which I want in future.
HTML
<input id="test" type="text" list="mylist"/>
<datalist id="mylist"></datalist>
JS
$(function() {
// assume this data is coming from ajax call
var data = [{
"name": "John",
"id": 1
}, {
"name": "Jane",
"id": 2
}, {
"name": "Judie",
"id": 3
}];
var generateDropDown = function(data) {
var datalist = $('#mylist');
for (var i = 0; i < data.length; i++) {
var value = data[i].name + ' => ' + data[i].id;
$('<option>', {
'class': 'myclass'
})
.val(value)
.data('extra', {
'newid': data[i] * 100
})
.appendTo(datalist);
}
};
generateDropDown(data);
$('.myclass').on('select', function(selected) {
console.log($(selected).data('extra'));
console.log($(this).data('extra'));
});
});
Here is the JSFiddle
My requirement is to access the selected value from drop down along with the data attribute i have added. How can I do that ?
I tried the 2 console.log options as mentioned above but they dont print anything.
In comparison to HTMLSelectElement object, HTMLDataListElement object doesn't have selectedIndex property, so it seems you have to filter the options for getting the possible selected option.
$('#test').on('change', function (/* event */) {
var val = this.value;
var data = $(this.list.options).filter(function() {
return this.value === val;
}).data('extra');
});
Here is a demo.
Also note that data[i] * 100 results in a NaN (Not a Number) value as you are multiplying an object by a number and it doesn't make any sense!
When using a datalist, think of it as just a list of suggestions for the user. The user can type whatever he/she wants. The option elements are not related to the actual selected value which is stored in the textbox. If you must use a datalist, then use an event on the textbox and select the option based on the value. Something like:
$('#test').on('change', function(selected) {
alert($("#mylist option[value='"+$(this).val()+"']").data('extra'));
});
This takes the textbox value and finds the associated datalist option. However, if I type some random gibberish, it won't and can't work since no corresponding option exists. The alternative is to use a select which forces the user to choose one of the options in the list.
If you want a select, take a look at https://jsfiddle.net/tscxyw5m/
Essentially now we can do:
$("#mylist").on('change', function() {
alert($(this).find("option:selected").data("extra"));
});
Because now the options are actually associated with the select.
Also note I think you meant:
'newid': data[i].id * 100
Not
'newid': data[i] * 100
Which yields NaN.
DEMO: https://jsfiddle.net/erkaner/9yb6km6a/21/
When you try to get the value of the selected item, you need to search through the options in the page and bring the option item that matches with the value in the input field:
$("#test").bind('input', function () {
alert($('body')
.find(
'option[value*="' + $(this).val() + '"]'
).data('extra').newid);
});
I use KendoUI ComboBox and I want to put a default select item.
In KendoUI ComboBox I didn't find the way to put the default value in text and not with index.
<script>
$("#combobox").kendoComboBox({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id"
});
var combobox = $("#combobox").data("kendoComboBox");
combobox.select(combobox.ul.children().eq(0));
</script>
Here is the example. How can convert it to put text?
As #SatyaRanjanSahoo says you should use value but you should use the id value otherwise you will be forcing a value that might not be in the DataSource.
Example, If you do:
var combobox = $("#combobox").data("kendoComboBox");
// Set Value
combobox.value("Apricot");
// Get Value
alert("Value is " + combobox.value());
this will show Apricot but this is not in the DataSource meanwhile, if you do:
var combobox = $("#combobox").data("kendoComboBox");
// Set Value
combobox.value(2);
// Get Value
alert("Value is " + combobox.value());
This will show Oranges that is the correct value for the item which id is 2.
So, unless you are sure that the value set in value call is a valid dataTextField I would recommend using the dataValueField.
Check this in the following code snippet...
$("#combobox").kendoComboBox({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id"
});
var combobox = $("#combobox").data("kendoComboBox");
// Set a valid value
combobox.value("Oranges");
alert("Value for Oranges is: " + combobox.value());
// Set an invalid value
combobox.value("Apricots");
alert("Value for Apricots is: " + combobox.value());
<link href="http://cdn.kendostatic.com/2014.2.1008/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.2.1008/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://cdn.kendostatic.com/2014.2.1008/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.2.1008/js/kendo.all.min.js"></script>
<input id="combobox"/>
To put text directly into combo-box:
var combobox = $("#combobox").data("kendoComboBox");
combobox.value("Oranges");
But, using the same approach anonymous text can be set into the combo-box which is not a part of the data-source. i.e.
combobox.value("XYZ");
So, its good to use index to set value to combo-box.
I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?