How can i put hidden id with autocomplete jquery - javascript

I want to put hidden id when get the value from autocomplete for add to database but now when i get value from autocomplete and add to database it's add value is label name not the id of the data
<input type='text' id='id' name='id' class='id_line' placeholder='Item Code'/>
This my jquery code
$("#add_line").on('click',function(){
$('.tbl_add_line').append(data);
$('.id_line').autocomplete({
source: function (request, response){
$.ajax({
url : "<?php echo site_url('warehouse/get_id');?>",
dataType: "jsonp",
data : {
q: request.term
},
success: function( data ) {
response(data);
}
});
},
});
i++;
});
And this is function to get data to show in autocomplete
function get_id(){
$result = "";
if(isset($_GET['q'])){
$code = $_GET['q'];
$this->db->like("item_code",$code)->select('*');
$this->db->order_by("item_code");
$result = $this->db->from("tbl_item_code")->get()->result();
}
$arr = array();
foreach($result as $key){
$arr[] = array(
'id' => $key->id,
'value' => $key->id,
'label' => $key->item_code."(".$key->id.")",
);
}
echo $_GET['callback']."(".json_encode($arr).")";
}

You can use _renderItem method to add custom attributes to created elements.
Try this:
$(function() {
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
}, {
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}, {
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}];
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
};
});
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<div id="project-label">
Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id" disabled>
<p id="project-description"></p>
Fiddle here

Related

How to get a row in Kendo UI TreeList / Grid?

I have a Kendo TreeList where I search for the row where myDataItem is (with help of the uid or value).
When I execute:
$("#treeList tbody").on("click", "tr", function (e) {
var rSelectedRow = $(this);
var getSelect = treeList.select();
console.log("'real' selected row: "+rSelectedRow);
console.log("selected row: "+getSelect);
});
and in another function, where I want to get a row (not the selected one, just a row where myDataItem is):
var grid = treeList.element.find(".k-grid-content");
var myRow = grid.find("tr[data-uid='" + myDataItem.uid + "']"));
//or
// myRow = treeList.content.find("tr").eq(myDataItem.val);
console.log("my row:" + myRow)
I get:
'real' selected row: Object [ tr.k-alt ... ]
selected row: Object { length: 0 ... }
my row: Object { length: 0 ... }
I need the same structure of rSelectedRow for myRow. So how can I get the ,real' tr-element?
UPDATE: I wrote this method to find the row of my new added item:
//I have an id of the item and put it in an invisible row in the treelist.
getRowWhereItem: function (itemId) {
treeList.dataSource.read();
$("#menuItemTree .k-grid-content tr").each(function (i) {
var rowId = $(this).find('td:eq(1)').text();
console.log(itemId);
console.log(rowId);
if (rowId == itemId) {
console.log("found");
console.log(itemId + " " + rowId);
var row = this;
console.log(row);
return row;
}
});
},
The each-iteration reaches all tr's until/except the new added one. Why?
Use the change event instead of binding a click event to the widget's DOM. Note that for change to work, you need to set selectable to true:
<!-- Orginal demo at https://demos.telerik.com/kendo-ui/treelist/index -->
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/treelist/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.3.911/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.3.911/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="treelist"></div>
<script id="photo-template" type="text/x-kendo-template">
<div class='employee-photo'
style='background-image: url(../content/web/treelist/people/#:data.EmployeeID#.jpg);'></div>
<div class='employee-name'>#: FirstName #</div>
</script>
<script>
$(document).ready(function() {
var service = "https://demos.telerik.com/kendo-ui/service";
$("#treelist").kendoTreeList({
dataSource: {
transport: {
read: {
url: service + "/EmployeeDirectory/All",
dataType: "jsonp"
}
},
schema: {
model: {
id: "EmployeeID",
parentId: "ReportsTo",
fields: {
ReportsTo: { field: "ReportsTo", nullable: true },
EmployeeID: { field: "EmployeeId", type: "number" },
Extension: { field: "Extension", type: "number" }
},
expanded: true
}
}
},
height: 540,
filterable: true,
sortable: true,
columns: [
{ field: "FirstName", title: "First Name", width: 280,
template: $("#photo-template").html() },
{ field: "LastName", title: "Last Name", width: 160 },
{ field: "Position" },
{ field: "Phone", width: 200 },
{ field: "Extension", width: 140 },
{ field: "Address" }
],
pageable: {
pageSize: 15,
pageSizes: true
},
/* See here */
selectable: true,
change: function() {
let $selectedItem = this.select(),
dataItem1 = this.dataItem($selectedItem),
uid1 = $selectedItem.data("uid"),
uid2 = dataItem1.uid,
dataItem2 = this.dataSource.getByUid(uid1);
console.log("selected item", $selectedItem);
console.log("dataItem", dataItem1);
console.log("dataItem(alternative way)", dataItem2);
console.log("uid", uid1);
console.log("uid(alternative way)", uid2);
}
});
});
</script>
<style>
.employee-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-left: 5px;
}
.employee-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
</style>
</div>
</body>
</html>
The part that really matters:
selectable: true,
change: function() {
let $selectedItem = this.select(),
dataItem1 = this.dataItem($selectedItem),
uid1 = $selectedItem.data("uid"),
uid2 = dataItem1.uid,
dataItem2 = this.dataSource.getByUid(uid1);
console.log("selected item", $selectedItem);
console.log("dataItem", dataItem1);
console.log("dataItem(alternative way)", dataItem2);
console.log("uid", uid1);
console.log("uid(alternative way)", uid2);
}
Demo
I didn't find a solution where I can get the tr by datauid.
But in my case, I took the id of the item and put it in an invisible row in the treelist.
Therefore, the method getRowWhereItem(itemId) in the question works well when making it execute after a successfull Ajax Call. With the callback from my ajax call, I load the new item and then the method can find the row. So the issue was that I had to have the uptodate data from my database.
Another issue was with contexts. The method getRowWhereItem(itemId) was a method of a namespace. I tried to call that method outside the namespace and couldn't get its return. Now, I moved the method into the same context where I call it.
(note: My development follows the MVC pattern, Administration is a Controller-class)
$.ajax({
url: General.createMethodUrl("Administration", "Admin", "Add_New"),
data: { parentItemId: parentOfNewId },
type: "POST",
dataType: "json",
success: function (response) {
if (response) {
var addedItem = $.parseJSON(response);
//waiting for callback because otherwise the window opens a few milliseconds before the properties are loaded and newRow cannot be find
tManag.ajaxCallSelectedEntry(addedItem.Id, treeList, function () {
newRow = tManag.getRowWhereItem(addedItem.Id);
});
jQuery(newRow).addClass("k-state-selected")
} else {
tManag.alertDialog(dialog, "Adding New Item Notification", response.responseText);
}
},
error: function (response) {
tManag.alertDialog(dialog, "Adding New Item Error", "Error");
}
});

How to make 2 dependent option field?

I want my capital_city autocomplete field to show only options that are related to country_name. So when choose a country in the second option field show only cities that are realted to the selected country. Thank you.
Here is my view.php:
<div class="filtering">
<form class="searchbox_1">
Country Name: <input type="text" class="search_1" name="country_name" id="country_name" />
City Name: <input type="text" class="search_1" name="capital_city" id="capital_city" />
Date from <input class="search_1" type="date" name="from_date" id="from_date"/>
Date to <input class="search_1" type="date" value = "<?php echo date('Y-m-d')?>" name="to_date" id="to_date"/>
<center><button class="submit_1" type="submit" id="LoadRecordsButton">Search</button>
<input class ="submit_1" type="reset" value="Clear fields!"></center>
</form>
</div>
<div id="countryTable"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#countryTable').jtable({
title: 'Country\'s',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'country_name ASC',
selecting: true,
multiselect: true,
selectingCheckboxes: true,
selectOnRowClick: true,
actions: {
listAction: 'get_country',
createAction: 'create_country',
updateAction: 'update_country',
deleteAction: 'delete_country'
},
fields: {
country_id: {
key: true,
list: false
},
country_name: {
title: 'Country Name',
width: '11%'
},
country_code: {
title: 'Country Code',
width: '11%'
},
surface_area: {
title: 'Surface Area (m<sup>2</sup>)',
width: '13%'
},
continent_name: {
title: 'Continent Name'
},
continent: {
title: 'Continent Code',
width: '12%'
},
population: {
title: 'Population'
},
capital_city: {
title: 'Capital City'
},
record_date: {
title: 'Record Date',
type: 'date',
displayFormat: 'mm/dd/yy',
create: false,
edit: false,
sorting: false
}
},
$('#country_name').autocomplete({
source: 'list_country',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#capital_city').autocomplete({
source: 'list_city',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#countryTable').jtable('load', {
country_name: $('#country_name').val(),
capital_city: $('#capital_city').val(),
from_date: $('#from_date').val(),
to_date: $('#to_date').val()
});
});
$('#LoadRecordsButton').click();
});
</script>
</div>
Here is my model.php:
public function get_country_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT country_name FROM country "
. "WHERE deleted=0 AND country_name LIKE '" . $searchTerm . "%' ORDER BY country_name ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['country_name'];
}
echo json_encode($row);
}
public function get_city_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT capital_city FROM country "
. "WHERE deleted=0 AND capital_city LIKE '" . $searchTerm . "%' ORDER BY capital_city ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['capital_city'];
}
echo json_encode($row);
}
Here is my controller.php:
public function list_country(){
$this->load->model('Country_model');
$this->Country_model->get_country_name();
}
public function list_city(){
$this->load->model('Country_model');
$this->Country_model->get_city_name();
}
I have been looking for days to find a solution. Please help me. :-) .
Try adding something like this:
$('#country_name').change({
/*some code here*/
});
Then, transfer your $('#capital_city').autocomplete({}) inside, like this:
$('#country_name').change({
var country = $(this).val();
$('#capital_city').autocomplete({
source: 'list_city_' + country, /*see explanation below*/
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
});
Every time the country name is changed, the source of cities for auto-completion also changes accordingly.
For that to work, group your cities list by country when you fetch them through your model.
I was not able to test this code, and it may need some tweaks to work for you, but I hope it gives you some ideas to solve your problem. Good luck!

Hide column in jQuery MultiColumn Autocomplete

I have a fine working jquery multicolumn autocomplete. Now i have to add a column which should be hidden. Basically its a ID of the values. So when the user selects the value i could able to get the ID of the selected row.
//Code:
<script type="text/javascript">
var autocompleteSource;
var colValues = [];
var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
$.ajax({
url: "/Home/LoadWorkflowDropdown",
datatype: 'json',
mtype: 'GET',
success: OnComplete,
error: OnFail
});
function OnComplete(result) {
autocompleteSource = $.parseJSON(result)
$.each(autocompleteSource, function () {
colValues.push([this.WorkflowName, this.WorkflowCategory, this.StatusName, this.UserName]);
});
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colValues,
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
}
</script>
Working Fiddle here
Here i have modified js code to add unique id to each record and to get that value when user selects a particular option from the auto-suggest list. Fiddle
HTML: Create a hidden field to store the id of selected option
<input type="hidden" name="selectedId" id="selectedId" />
JS: Added ids in the array and retrieved those ids in select function by index value.
var columns = [{
name: 'Color',
width: '100px'},
{
name: 'Hex',
width: '70px'}],
colors = [['Red', '#f00', '1'], ['Green', '#0f0', '2'], ['Blue', '#00f', '3']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
$('#selectedId').val(ui.item[2]);
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});

Jquery autocomplete doesn't work

I got the following code from jquery ui demo.
I did some minor modifications to that.
Here is the modified code.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Custom data and display</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!--link rel="stylesheet" href="/resources/demos/style.css"-->
<style>
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-description {
margin: 0;
padding: 0;
}
</style>
<script>
$(function() {
var projects = [
{
id: "jquery",
name: "jQuery",
location: "the write less, do more, JavaScript library"
},
{
id: "jquery-ui",
name: "jQuery UI",
location: "the official user interface library for jQuery"
},
{
id: "sizzlejs",
name: "Sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.name );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.name );
$( "#project-id" ).val( ui.item.id );
$( "#project-description" ).html( ui.item.location );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.name + "<br>" + item.location + "</a>" )
.appendTo( ul );
};
});
</script>
</head>
<body>
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
<p id="project-description"></p>
</body>
</html>
Now jquery pops up autocomplete suggestions only when 'j' key is pressed.
for other keys it doesn't do anything.
what am I doing wrong here?
It is because of the default search mechanism, it filters the contents based on the fields label or value.
With your custom data, it is better to implement the source method yourself like,
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var array = $.grep(projects, function (value) {
return matcher.test(value.id) || matcher.test(value.name) || matcher.test(value.location);
});
response(array);
},
focus: function (event, ui) {
$("#project").val(ui.item.name);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.id);
$("#project-description").html(ui.item.location);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.location + "</a>")
.appendTo(ul);
};
Demo: Fiddle
You must have a value attribute on your projects array:
var projects = [
{
id: "jquery",
name: "jQuery",
value:"jQuery",
location: "the write less, do more, JavaScript library"
},
...
{
id: "sizzlejs",
name: "sizzle JS",
value:"sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
This way the search engine is going to work.

rowdata is undefined

I am struggling to see where I am getting an error of 'rowdata is undefined'? when I run my script and press the delete button. I am using jqxwidgets grid:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm
If someone could help out new user or how I can troubleshoot in firebug 1.9, I would be grateful. I have included my code for your inspection. Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.classic.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqx-all.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdatetimeinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcalendar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxtooltip.js"></script>
<script type="text/javascript" src="../../jqwidgets/globalization/jquery.global.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// prepare the data
var source =
{
datatype: "json",
datafields: [
{ name: 'id'},
{ name: 'type'},
{ name: 'service'},
{ name: 'quantity'},
{ name: 'department'},
{ name: 'date', type: 'date', format: 'yyyy-MM-dd HH:mm:ss'},
],
url: 'data.php',
updaterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "update=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowdata);
}
});
},
deleterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowid);
console.log(rowid);
}
});
}
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
source: source,
theme: 'classic',
width: 900,
altrows: true,
pageable: true,
sortable: true,
filterable: true,
autoheight: true,
pagesizeoptions: ['10', '20', '30', '40'],
editable: true,
ready: function () {
var button = $("<input type='button' value='Add' id='myButton'/>");
button.jqxButton({ height: 20 });
button.click(function () {
$("#jqxgrid").jqxGrid('addrow', null, []);
});
$(".jqx-grid-pager > div:first").append(button);
},
ready: function () {
//var value = $('#jqxrid').jqxGrid('deleterow', rowid);
var delbutton = $("<input type='button' value='Delete' id='DelButton'/>");
delbutton.jqxButton({ height: 20 });
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id);
});
$(".jqx-grid-pager > div:first").append(delbutton);
},
columns: [
{ text: 'id', editable: false, datafield: 'id', width: 100 },
{ text: 'Type', datafield: 'type', width: 150},
{ text: 'Service', datafield: 'service', width: 150 },
{ text: 'Quantity', datafield: 'quantity', width: 180 },
{ text: 'Department', datafield: 'department', width: 90 },
{ text: 'Date', datafield: 'date', columntype: 'datetimeinput', cellsformat: 'dd/MM/yyyy HH:mm:ss', width: 230, showCalendarButton: false }
]
});
});
</script>
</head>
<body class='default'>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var theme = 'classic';
// Create a jqxDateTimeInput
$("#jqxWidget").jqxDateTimeInput({ width: '250px', height: '25px', theme: theme, formatString: 'dd/MM/yyyy HH:mm:ss' });
});
</script>
<div id='jqxWidget'>
</div>
</div>
<div id="jqxgrid"></div>
</body>
</html>
You are invoking deleterow() without the proper parameters :)
Signature:
deleterow: function (rowid, rowdata) {}
Invocation:
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id /* Missing argument */ );
});
You should add the rowdata as an argument. I don't think this code is to be considered very safe.. (which could be rewritten anyways, skipping the "data = data +", see below ).
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
You can obtain the rows as follows (
You should ask for a confirmation, first! ):
delbutton.click(function () {
var rows = $('#grid').jqxGrid('getrows'),
selectedRowIndex = $('#grid').jqxGrid('getselectedrowindex'),
selectedRow = rows[ selectedRowIndex ];
if( confirm("Are you sure you wish to delete the row with index '" + selectedRowIndex + "'?") {
$('#jqxgrid').jqxGrid('deleterow', selectedRowIndex, selectedRow );
}
});
This would be more readable and usable:
var data = [
"delete=", "true",
"&type=", rowdata.type,
"&service=", rowdata.service,
"&quantity=", rowdata.quantity,
"&department=", rowdata.department,
"&date=", rowdata.date,
"&id=", rowdata.id
].join("");
Actually I think the following might make it more complex and less errorprone, but easier to use:
// Another solution
var customDataProperties = {
"delete": "true"
// ,"another": 2
}
var rowdataProperties = [
"type",
"service",
"quantity",
"department",
"date",
"id"
];
function getData( rowdataObject ) {
// Add additional
var data = [];
function createParameterSetString( property, value ) {
return [ "&", property, "=", value ].join("");
}
for( var propertyName in customDataProperties ) {
data.push( createParameterSetString( propertyName, customDataProperties[ propertyName ] ) );
}
for( var i = 0, ln = rowdataProperties.length; i < ln; i++ ) {
var property = rowdataProperties[i];
data.push( createParameterSetString( property, rowdataObject[ property ] ) );
}
if( data.length != 0 ) { data.pop( 0 ); }
return data.join("");
}
As you can see, you can easily extend parameters this way.

Categories