Default select kendo combobox - javascript

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.

Related

How to pass a variable selector to jquery .attr()

This is the scenario. In a jQuery DataTable I have some value and an edit button to modify 2 of them; clicking on it, a modal popup is opened and offer a form to insert the new value for notes and status:
...
"columnDefs": [
{
"targets": [ 0 ],
"visible": false
//"searchable": false
}],
"columns": [
{ "data": "id" },
{ "data": "date" },
{ "data": "type" },
{ "data": "name" },
{ "data": "user_name" },
{ "data": "status" },
{ "data": "closing_date" },
{ "data": "info" },
{ "data": "note" },
{ "data": null,
"render": function ( data, type, full, meta ) {
return "<button type='button' class='btn btn-info btn-md' id=\'" + full.id + "\' data-toggle='modal' data-id=\'" + full.id + "\' data-target='#myModal'> Edit </button>";
}
...
Immediately below, I have the ajax function to send the inserted value to a Spring controller:
//This function is used to send the form data to Spring controller; cause we use a modal, with code that must be put in the file with html table head,
//we must replace the use of view made by jsp using an ajax function
$('#myModal').on('click', '.btn.btn-success', function(event) {
var form = $('#updateeventsform'); //recover the form inside modal by using id
var formdata = form.serializeObject(); //use the serializeObject function to prepare data for Json format
formdata.idevent = $(this).attr('data-id'); //add the event id to form data, after setting it with the IDnumber variabile
console.log(formdata, this);
event.preventDefault();
//here starts the code to sending data to Spring controller
$.ajax({
url: "../updateevents.json",
type: "post",
data: formdata,
success : function() {
console.log("Invio riuscito.");
DTevents.ajax.reload( null, false ); //we reload the table, showing immediately the data updated.
}
});
});
This code give me an undefined value on formdata.idevent; and it's right, because the $(this) value refers to the current element (in my case, the submit button).
As you can see, the id for the button is a numeric value, setted with the full.id field.
So, I've got a try: put a numeric value as selector for attr() function. I changed:
formdata.idevent = $(this).attr('data-id');
in
formdata.idevent = $('#5').attr('data-id');
and this works.
So, the question is: is there a way to use a variable value as selector for the .attr() function? If no, what should I use to pass the correct value to the controller?
Edit for comment answer.
Already used $(this).data('id'); does not works. I got undefined values for idevent.
<button type='button' class='btn btn-info btn-md' **id=\'" + full.id +**
here you can note the numeric id of button element.
The intent is: this table represent events. When the 2 fields modified, notes and status, must be send to the controller, i Must send also the events id to it and i want perform this with the use of .attr() function.
Now, this function must be used on a selector; i may want use the button id as selector but I have different button with different id. So, if i click the 4th button, the id is 4 and I may have:
formdata.idevent = $['#4'].attr('data-id');
if I click the 5th button the code must be:
formdata.idevent = $['#5'].attr('data-id');
if I click the 6th button:
formdata.idevent = $['#6'].attr('data-id');
and so on. So, I have a variable selector to use; I don't know how to perform this.
I would try to add an hidden input to the modal...
<input type="hidden" id="idevent" name="idevent">
And on a "Edit" button click, carry its id to the modal form:
$(".btn.btn-info").on("click",function(){
var idevent = $(this).data("id"); // Or $(this).attr("id")
// Delay for the modal openning animation...
setTimout(function(idevent){
$('#myModal form #idevent').val(idevent);
},800);
});
Then, the info would already be in the form when user submits it.;)

Kendo AutoComplete Default Value

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.

jquery get data attributes from dynamically generated options

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);
});

How to dynamically create a form element

I have the following code
I am trying to dynamically create radio button with and without labels in them. I am unable to put the text in radio button when I create radio button, here is the code without labels
This is what expect
<input type="radio" name="Alex" value="Alex"/>Alex
$('<input>').attr({
type:'radio',
name:'name',
value: "Alex",
text:"Alex"
}).insertAfter("#divid"));
Now for having labels,
<label><input type="radio" name="Alex" value="Alex"/>Alex<label>
//create a label tag
var label = $('<label>', { text:"Alex"});
//append input tag to label
$(label).append($('<input>').attr({
type:'radio',
name:"Alex",
value:"Alex"
}).insertAfter("#divid"));
Both of the above does not produce any error on console but it does not produce the right HTML tag I am interested in. Also is there a way to directly add label to radio as I create them dynamically. I mean I dont want to create a label tag separetely and append to it the radio button. Many Thanks for your help
Dynamically create label and radio
jsBin example
var $input = $('<input />', {
type : "radio",
name : "name",
value : "alex"
});
$("<label />", {
insertAfter: "#somediv", // (or use appendTo: to insert into it)
append: [$input, "Alex"] // include our $input and also some text description
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="somediv">DIV</div>
You should replace var label = $('<label>').attr({ text:"Alex"}); with var label = $('<label>').text("Alex");
Also - you have few syntax errors in your code, I don't see what's so hard to copy+paste properly.
I like Roko's answer, except that it's vulnerable to HTML injection if you're building the radio button labels from user content.
Here, I use the .text() method to make sure that the text is properly escaped.
var $target = $('#target'),
records = [{ id: 1, name: "Alex" },
{ id: 2, name: "Test that HTML <em>is not</em> injected" }];
$target.append('<h3>With Labels</h3>');
for (var i=0; i < records.length; i++) {
$target.append($('<label>').text(records[i].name)
.prepend($('<input type="radio" name="mychoice">',
{ value: records[i].id })));
}
$target.append('<h3>Without Labels</h3>');
for (var i=0; i < records.length; i++) {
$target.append($('<span>').text(records[i].name)
.prepend($('<input type="radio" name="mychoice">',
{ value: records[i].id })));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>

Issue with JSON parsing

I am a complete noob with JSON parsing in jQuery. Thought I got the response... My data is in this form:
Array(
[1]=>abc,
[3]=>mango,
[4]=>apple,
[5]=>fruits
)
In this way I want this list to appear as an autocomplete list. I am using.
jQuery("#name").autocomplete( '<?php echo HTTP_PATH.'/songs/sss'; ?>', {
multiple: true,
mustMatch: true,
matchContains: true,
autoFill: false,
dataType: "json",
parse: function(data) {
return jQuery.map(data, function(item) {
return { data: item, value: item.label, result: item.label};
});
},
formatItem: function(item) {
return item.label;
},
formatResult: function(item) {
return item.id;
},
formatMatch: function(item) {
return item.label;
}
});
I want the value when it shows list, i.e. the label from my data. When I select a label then it should show the label. But at the time of submission it should actually submit the key.
I mean I want it to work as select box of HTML.
Returned JSON
[{"id":1,"label":"Mehdi Hassan"},{"id":2,"label":"Jagjit Singh"},{"id":3,"label":"Suresh Vadekar"}]
Your JSON seems to not be an array, just an object (hash map).
Check out official docs:
Expected data format
The data from local data, a url or a callback can come in two
variants:
An Array of Strings: [ "Choice1", "Choice2" ]
An Array of Objects with label and value properties: [ { label: "Choice1", value: "value1" },
... ]
In your case it should be in the following format:
[
{"1":"Shad.aab"},
{"158":"Adadad"},
{"159":"Asdadad"},
{"166":"Abbas"},
{"167":"Sdadad"},
{"171":"Shadaab Please check it out"},
{"173":"Check This Please"},
]
(Remember that left side is label, right value, I suppose in your data, all should be reversed...)
If I understand you correctly, you want to use autocomplete to populate a name textfield, but want to leverage another value associated w/ the name in the form POST.
[If you're able to use latest jQueryUI version of autocomplete] - Following the "Custom Data and Display" autocomplete example at http://jqueryui.com/demos/autocomplete/#custom-data, you'll see that on autocomplete hint, they display the selected label, however, they also save an associated value in a hidden input that is also posted back to server. Given your current json format:
html:
<label for="username">Name:</label>
<input id="username" size="50" /> <!-- holds display name -->
<input id="userid" name="userid" size="50" /> <!-- holds userid -->
...
js:
<script>
$("#username").autocomplete({
source: '<?php echo HTTP_PATH.'/songs/sss'; ?>',
// Update display name when user mouses over selection
focus: function( event, ui ) {
$( "#username" ).val( ui.item.label );
return false;
},
// Set display name and hidden input on user selection
select: function( event, ui ) {
$( "#username" ).val( ui.item.label );
$( "#userid" ).val( ui.item.id );
return false;
}
});
</script>
php POST target:
<?php
// Use [hidden] input to do your magic
if(isset($_POST['userid']))
echo 'Wooo..here is my key: ' . $_POST['userid'];
?>
The problem looks like it's here:
jQuery("#name").autocomplete( '<?php echo HTTP_PATH.'/songs/sss'; ?>', { multiple: true, ...
It should be like this:
jQuery("#name").autocomplete( { source: '<?php echo HTTP_PATH.'/songs/sss'; ?>', multiple: true, ...
Also make sure you are using it on load/ready and not just inside a plain <script> tag
$(function(){ jQuery("#name").autocomplete(); });
Use firebug to verify that when you type a letter in that field it sends a request to the source page set for autocomplete.
Here is the code I used to re-create/fix your problem:
index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.20.custom.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
$(function(){
jQuery("#name").autocomplete({
source: 'index_json.php',
multiple: true,
mustMatch: true,
matchContains: true,
autoFill: false,
dataType: "json",
parse: function(data) {
return jQuery.map(data, function(item) {
return { data: item, value: item.label, result: item.label};
});
},
formatItem: function(item) {
return item.label;
},
formatResult: function(item) {
return item.id;
},
formatMatch: function(item) {
return item.label;
}
});
});
</script>
</head>
<body>
<form>
<label for="name">Name: </label>
<input id="name" name="name" />
</form>
</body>
</html>
index_json.php
<?
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo '[{"id":1,"label":"Mehdi Hassan"},{"id":2,"label":"Jagjit Singh"},{"id":3,"label":"Suresh Vadekar"}]';
?>
I am very confused with your request, but have taken your code and made it work how you specified (I think).
I want value when it show list.i.e. Label from my data. When I select label than also it should show label. but at time of submission it should actually submit key. I mean i want it to work as select box of HTML.
It almost sounds as if you want an input box for just searching and a static select list that changes from autocomplete but stays there instead of disappearing...
You need to do json_encode($your_array) in backend.
It will convert PHP Array into your JSON encoded strings that your front-end (jQuery) can then parse and process.
I am not sure I understood your question well. But I faced the same kind of requirement in my experience. I used ajax autocomplete js from the above link. (Go thru the link for complete details)
The highlight here is, this js provides you a callback onSelect with which you can set your values after selection of the auto complete suggestion.
The json encoded string should be like
query:'Li',
suggestions:['Mahendi Hassan','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['1','2','3','4']
query - original query value
suggestions - comma separated array of suggested values
data (optional) - data array, that contains values for callback function when data is selected.
Now have some hidden input field in your form, and set the selected suggestion's data to value of that hidden input field like this.
jQuery(function () {
options = {
minChars: 2,
serviceUrl: "ur/php file",
onSelect: function (value, data) {
$('#hiddenUserProfileIdProps').val(data); //Setting value to hidden field
}
});
a = $('#enterEmailLink').autocomplete(options);
a.disable();
});
Then submit your form. Thats it.

Categories

Resources