autocomplete searches work, but not gets selected - javascript

Input text boxes are created dynamically via jquery. Autocomplete works well. But when I select an item its value is not rendered properly, May I know where am I missing here ?
Jquery
$(function() {
var projects = [
{
"label": "ajax",
"value": "1003",
"desc": "foriegn"
},
{
"label": "jquery",
"value": "1000",
"desc": "dd"
},
{
"label": "wordpress theme",
"value": "1000",
"desc": "h"
},
{
"label": "xml",
"value": "1000",
"desc": "j"
} ];
$("#addButton");
var counter = 13;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'project-description' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'project' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'project-id' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#project" + counter).autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project" + counter).val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project" + counter).val(ui.item.label);
$("#project-id" + counter).val(ui.item.value);
$("#project-description" + counter).val(ui.item.value);
$("#project-icon" + counter).attr("src", "images/" + ui.item.icon);
return false;
}
})
counter++;
});
});
`
Html is below
<div id="project-label"></div>
<input id="project" />
<input type="hidden" id="project-id" />
<input type="text" disabled="disabled" id="project-description"></p>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
</div>
</div>
<input type='button' value='Add' id='addButton' />
Please tell me what am I missing in this piece of code.

I think it's a JavaScript error. Your select event from the autocomplete looks for $("#project-icon" + counter), but I don't see that element being rendered anywhere. Also, when trying to set the src attribute of that element, you reference ui.item.icon, but your array of values doesn't contain that property.

Related

How to get value textbox in datatable column jquery and push to a variable?

I want to get a value of 53.54.57 but somehow I always get the value of 53.53.53 not as expected. anyone can help me?
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{ data: 'harga' },
{ data: 'qty' },
{ data: 'total' },
{ data: 'remove' },
{ data: 'untung' },
]
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
$("#" + $(data.remove).attr("id")).val();
I use this function to retrieve data from the datatable, but the line can only be the same value. always a value of 53, how to get the value of a line in the column called 'remove'
Is my looping wrong? or is there another way to get that value?
Like #charlietfl said, it seems you're duplicating the element ids.
If I understood you correctly, and the id of your input(type number) is the value, then you only need to change one line:
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
//change this line
//master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
//for this one
master_barang_id = $("#" + data.remove).val();
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
This is a working example:
var jsonData = [{ "linenum": 1, "nama": "lampu economat 3w LED", "harga": 20000, "qty": 1, "total": 20000, "remove": 53, "untung": "X" }, { "linenum": 2, "nama": "lampu economat 5w LED", "harga": 25000, "qty": 1, "total": 25000, "remove": 54, "untung": "X" }, { "linenum": 3, "nama": "lampu economat 9w LED", "harga": 30000, "qty": 1, "total": 30000, "remove": 57, "untung": "X" }];
$("#btnGetData").click(function() {
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id = $("#" + data.remove).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
});
var oTable = $('#table-main').DataTable({
data: jsonData,
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{
data: 'harga',
"render": function (data, type, row, meta) {
return '<input type="text" value=' + data + ' />';
}
},
{
data: 'qty',
"render": function (data, type, row, meta) {
return '<input type="number" value=' + data + ' />';
}
},
{ data: 'total' },
{
data: 'remove',
"render": function (data, type, row, meta) {
return '<input type="number" id="' + data + '" value=' + data + ' />';
}
},
{ data: 'untung' },
]
});
input {
text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<div class="data-table-container">
<table id="table-main" class="table cell-border order-column stripe">
<thead>
<tr>
<th>linenum</th>
<th>nama</th>
<th>harga</th>
<th>qty</th>
<th>total</th>
<th>remove</th>
<th>untung</th>
</tr>
</thead>
</table>
</div>
<br>
<input type="button" id="btnGetData" value="GET DATA" />

jQuery autocomplete suggests all options regardless of input entry

I have a jQuery script that will get a JSON response and create as many "player" objects as there are in the response.
It will then add to availablePlayers which I then use as the variable for the source: field of autocomplete
When a user selects a player name and clicks the "add" button it will, at the moment, just display the guid and name of a player.
However, no matter what letters I type, all the players are given as an option. To illustrate this, if I type "Z" and none of the players have Z in their name, they options are still displayed.
How can I refine this functionality?
HTML
<div class="player-widget">
<label for "players">Players</label>
<input id="player" />
<input id="playerGUID" hidden />
<button id="add">Add</button>
</div>
jQuery
$(document).ready(function(){
var availablePlayers = []; // BLANK ARRAY OF PLAYERS
$("#player").autocomplete({
source: availablePlayers,
response: function (event, ui) {
ui.content = $.map(ui.content, function(value, key) {
return {
label: value.name,
value: value.guid
}
});
},
focus: function(event, ui) {
$("#player").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#player").val(ui.item.label); // display the selected text
$("#playerGUID").val(ui.item.value); // save selected id to hidden input
return false;
}
});
$.getJSON("http://localhost/Websites/Player-Widgets/service.php", function(data) {
var feedHTML = '';
// LOOP THROUGH EACH PLAYER
$.each(data.players, function(i, player) {
// DEFINE VARIABLES - BASED ON PLAYER ATTRIBUTES
var guid = player.guid;
var name = player.name;
var dob = player.date_of_birth;
var birth = player.birthplace;
var height = player.height;
var weight = player.weight;
var position = player.position;
var honours = player.honours;
// CREATE NEW PLAYER (OBJECT)
var player = {
guid: guid,
name: name,
position: position
};
// ADD TO PLAYER TAG ARRAY
availablePlayers.push(player);
});
console.log("User friendly array");
$.each(availablePlayers, function(i, val) {
console.log(val.guid + " - " + val.name + " [" + val.position + "]");
});
console.log("Array printout");
console.log(JSON.stringify(availablePlayers));
}).done(function(){
console.log("Done! Success!");
$("#player").autocomplete("option", "source", availablePlayers);
});
$("#add").click(function() {
alert($("#playerGUID").val() + " - " + $("#player").val());
});
});
Sample JSON response
{
"players": [
{
"guid": "1",
"name": "Matias Aguero",
"date_of_birth": "1981-02-13",
"birthplace": "San Nicolas, Argentina",
"height": "1.83m (6' 0\")",
"weight": "109kg (17st 2lb)",
"position": "Prop",
"honours": "40 caps"
},
{
"guid": "2",
"name": "George Catchpole",
"date_of_birth": "1994-02-22",
"birthplace": "Norwich, England",
"height": "1.85em (6ft 1\")",
"weight": "104kg (16st 5lb)",
"position": "Centre",
"honours": ""
}
]
}
Your problem is in the source function.
Source function uses request to pass term param to query, and you are ignoring it.
If you're using availablePlayers to query, you should use
source: availablePlayers
and your current function to map {label, text} object in response parameter.
response: function (event, ui) {
ui.content = $.map(ui.content, function(value, key) {
return {
label: value.name,
value: value.guid
}
});
}

Select2.js: why is id the same as text on change for removed?

JSfiddle: http://jsfiddle.net/cjVSj/
I have a simple select2 with the range of possible tags set by the tags option and the preloaded tags set by values in the input field in the html.
When the on change event fires on the select2, the removed item seems to lose its id, reporting instead its text value.
To see the problem, adding a tag (e.g. west) correctly reports the added.id, but removing the existing east tags reports id = east, not 1356.
Any insight into how to gain access to the id of a tag upon removal?
HTML:
<script>
var tags = [{ "id": 1354, "text": "north", "restricted": false
}, {"id": 1355, "text": "south", "restricted": false
}, {"id": 1356, "text": "east", "restricted": false
}, {"id": 1357, "text": "west", "restricted": false
}];
</script>tags:
<input type="text" id="mytags" value="east" />
JS:
$(document).ready(function () {
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id)
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id)
}
});
});
There was an issue with your select2 declaration and syntax.
Further more, if you entered any other text, say "eas" or "test", your piece of code reflected that as it is. Check this scenario.
Updated fiddle: http://jsfiddle.net/ZBf5H/
To be specific, you did not give appropriate mapping to your tags. Please find how to access remote data in select 2 from here
The change of code is as below:
$(document).ready(function() {
var data=[{id:1354,text:'north',restricted:false},
{id:1356,text:'east',restricted:false},
{id:1357,text:'west',restricted:false},
{id:1355,text:'south',restricted:false}];
function format(item)
{ return item.text; }
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
data:{ results: data, text: 'text' },
formatSelection: format,
formatResult: format
});
Let me know if this works for you.
Ok... I've got a working solution, but I still don't exactly understand the difference between select2's tags and data options....
JSfiddle: http://jsfiddle.net/7e8Pa/
I'm initializing select2 with a list of all possible tags via the data option from an array, then selecting those for preloading: the initSelection function checks for ids in the and looks them up in the data array (the pre-stored one, not Select2's). Last, new tags may be added (the createSearchChoice does this). To hook this to my server, I'm just going to insert ajax calls where noted below in the on-change event handler (which gets called after createSearchChoice, and can overwrite the field values for the new object set in createSearchChoice).
JS:
function findWithAttr(array, attr, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] == value) {
return array[i];
}
}
}
$(document).ready(function () {
function format(item) {
return item.text;
}
$('#mytags').select2({
placeholder: 'Search',
minimumInputLength: 2,
multiple: true,
//tags: tags,
tokenSeparators: [','],
data: {
results: tags,
text: 'text'
},
initSelection: function (element, callback) {
var data = [];
$($('#mytags').val().split(",")).each(function (i) {
var o = findWithAttr(tags, 'id', this);
if (o) {
data.push({
id: o.id,
text: o.text
});
} else {
console.log("findWithAttr returned none; likely invalid id");
}
});
console.log("data = " + JSON.stringify(data));
callback(data);
},
createSearchChoice: function (term, data) {
console.log("create");
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// call $.post() to add this term to the server, receive back id
// return {id:id, text:term}
// or detect this shiftiness and do it below in the on-change
return {
id: -1,
text: term
};
}
},
formatSelection: format,
formatResult: format
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id);
//modifying the id here overrides what is assigned above in createSelection
e.added.id = 5;
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id);
}
var selections = (JSON.stringify($('#mytags').select2('data')));
$('#selectedText').text(selections);
});
});
HTML:
<script>
var tags = [{
"id": 1354,
"text": "north",
"restricted": false
}, {
"id": 1355,
"text": "south",
"restricted": false
}, {
"id": 1356,
"text": "east",
"restricted": false
}, {
"id": 1357,
"text": "west",
"restricted": false
}];
</script>
<p>tags:
<input type="text" id="mytags" value="1355" style="width:80%" />
</p>
<p>Selected Options: <span id="selectedText"></span>
</p>
<p>Debug: <span id="debug"></span>
</p>

Kendo Grid with Kendo Dropdownlist Selected value not updated

In my kendo grid, i have kendodropdownlist for each column. A selected item should resolve and also show the template text
i have been following the example here http://jsfiddle.net/jddevight/Ms3nn/
UPDATE
I have simplified my issue in here http://jsfiddle.net/BlowMan/mf434/
Problem
When i select a an item in the dropdown, it does not return the value of the selected item. It rather returns null.
/// <reference path="../../jquery-1.8.2.js" />
/// <reference path="../../kendo.web.min.js" />
$(function () {
var menuModel = kendo.data.Model.define({
fields: {
"MenuId": { type: "number",editable:false },
"DisplayText":{type:"string"},
"MenuOrder": { type: "number" },
"MenuStatus": { type: "boolean" },
"HasKids": { type: "boolean" },
"ParentMenu": { type: "number" }
}
});
var menuDataSource = new kendo.data.DataSource({
data:[{"MenuId":1,
"DisplayText":"Home",
"MenuOrder":0,
"MenuStatus":true,
"HasKids":false,
"ParentMenu":null},
{"MenuId":2,
"DisplayText":"Finance",
"MenuOrder":1,
"MenuStatus":true,
"HasKids":false,
"ParentMenu":null}]
schema: {
model: menuModel
}
});
var vm = kendo.observable({
menus: menuDataSource,
parentItem: [{ Id: 2,
Name: "Finance" },
{ Id: 3,
Name: "Corp Services" }],
getMenuName: function (pMenu) {
var menuName = "";
$.each(this.parentItem, function (idx, menu) {
if (menu.Id == pMenu) {
menuName = menu.Name;
return false;
}
});
return menuName;
}
});
kendo.bind($("#menuItems"), vm);
var parentMenuEditor = function (container, options) {
$("<input name='" + options.field + "'/>")
.appendTo(container)
.kendoDropDownList({
dataSource: {
data:[{ Id: 2, Name: "Finance" }, { Id: 3, Name: "Corp Services" }],
},
dataTextField: "Name",
dataValueField: "Id"
});
};
var grid = $("div[data-role='grid']").data("kendoGrid");
$.each(grid.columns, function (idx, column) {
if (column.field == "ParentMenu") {
column.editor = parentMenuEditor;
return false;
}
});
});
The view section below
#{
ViewBag.Title = "Menu System Index";
}
<h2>Menu System Index</h2>
<div id="menuItems">
<div class="k-toolbar k-grid-toolbar">
<a class="k-button k-button-icontext k-grid-add" href="#">
<span class="k-icon k-add"></span>
Add Person
</a>
</div>
<div data-role="grid"
data-bind="source: menus"
data-editable="true"
data-filterable="true"
data-columns='[{"field": "MenuId", "title": "MenuId"},
{"field": "DisplayText", "title": "DisplayText"},
{"field": "MenuOrder", "title": "MenuOrder"},
{"field": "MenuStatus", "title": "MenuStatus"},
{"field":"HasKids","title":"HasKids"},
{"field":"ParentMenu","title":"ParentMenu","template":"#= parent().parent().getMenuName(ParentMenu) #"},
{"command": "destroy", "title": " ", "width": "110px"}]'>
</div>
</div>
<script type="text/x-kendo-template" id="toolbar-template">
<a class="k-button k-button-icontext k-grid-add" href="\#"><span class="k-icon k-add"></span>Add new record</a>
</script>
#section scripts{
<script src="~/Scripts/Custom/MenuSystem/Index.js"></script>
}
Any assistance will be much appreciated. This problem has me on my knees.
I have updated your JsFiddle demo. Please check it and let me know if any concern.
var roleEditor = function(container, options) {
$("<input name='" + options.field + "' data-text-field='name' data-value-field='id' data-bind='value:" + options.field + "'/>")
.appendTo(container)
.kendoDropDownList({
dataSource: {
data: vm.roles
},
dataTextField: "name",
dataValueField: "id"
});
};

How to output data as HTML from JSON object using getJSON

Hello there I will try and keep this simple and short
I have a getJSON function that runs every 5 seconds. Now when I display the data using document.write function it dosent seem to want to update. The page is stuck in a loading loop. How can I get the data to display on my page? My JSON is fine but I will show you anyways.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){ $.getJSON('names.json', function(data) {
for(i in data) {
document.write(data[i] + "<br/>");
}
});
},5000);
</script>
This is the JSON object
{
"one": "",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Don't actually use document.write. Once the page is loaded, that will erase the page. Use (jQuery's) DOM methods to manipulate the DOM.
$.getJSON('names.json', function(data){
for(var i in data){
$('#myDiv').append(data[i]);
}
});
I would recommend you use jQuery,
I used this to create a form from my json item, I hope this helps...
function jsonFormCreator(frmJSON)
{
var createdHTML = ""; var elementType, id;
console.log(JSON.stringify(frmJSON));
for(item in frmJSON)
{
formElement = frmJSON[item]; elementType = formElement.elementType; id = formElement.id;
if(elementType == "input")
{
createdHTML += "<input id='" + id +"'";
if(formElement.type == "checkbox")
{createdHTML += " type='" + formElement.type + "' checked='" + formElement.checked + "'";}
else{createdHTML += "type='" + formElement.type + "' value='" + formElement.value + "' onclick='" + formElement.onclick + "'";}
createdHTML += "/><br>"
}
else if(elementType == "textarea")
{createdHTML += "<textarea id='" + formElement.id + "' rows='" + formElement.rows + "' cols='" + formElement.cols + "' value='" + formElement.value + "'></textarea><br>";}
else if(elementType == "select")
{
var options = formElement.values;
createdHTML += "<select id='" + formElement.id+ "'>";
for(i = 0 ; i < options.length ; i++)
{createdHTML += "<option value='" + options[i][0] + "'>" + options[i][1] + "</option>";} //Adding each option
createdHTML+= "</select><br>";
}
}
console.log("Complete");console.log(createdHTML);
document.getElementById('mainContainer').innerHTML = createdHTML;//Adding to the DOM
}
And my JSON would look like this
{
"0": {
"elementType": "input",
"id": "frm1",
"type": "text",
"value": "form Liam",
"label": "Test Text Input"
},
"itemBTN": {
"elementType": "input",
"id": "frmAlert",
"type": "button",
"onclick" : "loader(homePage);",
"value": "Home Page",
"label": ""
},
"item2": {
"elementType": "textarea",
"id": "frm2",
"rows": 5,
"cols": 30,
"value": "helddddddddlo",
"label": "Test Textarea"
},
"item3": {
"elementType": "select",
"id": "frm3",
"values": [
[
"value1",
"Pick Me"
],
[
"value2",
"UserDis2"
],
[
"value3",
"UserDis3"
],
[
"value4",
"UserDis4"
],
[
"value5",
"UserDis5"
],
[
"value6",
"UserDis6"
]
],
"label": "Test Select"
},
"item4": {
"elementType": "input",
"id": "frm4",
"label": "Checkbox",
"type": "checkbox",
"checked": true
}
}
This code adds the form in to my div tag with the id mainContainer
I know its alot of code, but i hope it helps !
You want to render dom which will contain the data, then when you get the data update the dom.
As an exceedingly simple example, on your page have a container
<div id="one"></div>
and then in your ajax success handler
$("#one").text(json.one);
This uses jquery to grab the dom element with id "one", and update its text.

Categories