make jquery plugin not share private variable in same plugin - jquery-plugins

<script>
(function () {
jQuery.fn.szThreeStateColor = function (settings) {
var cfg = {
"overBgColor": "green",
"overFgColor": "white",
"clickBgColor": "blue",
"clickFgColor": "white"
};
if(settings) {
$.extend(cfg, settings);
}
var clickIdx = -1;
$thisObj = $(this);
var iniBgColor = $thisObj.find("tbody td").css("background-color");
var iniFgColor = $thisObj.find("tbody td").css("color");
var iniHeight = $thisObj.find("tr").css("height");
$thisObj.find("tbody tr").bind("mouseover", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": cfg.overBgColor,
"color": cfg.overFgColor
});
}
});
$thisObj.find("tbody tr").bind("mouseout", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
});
$thisObj.find("tbody tr").bind("click", function (e) {
//console.log($(this).index() + ":" + clickIdx);
if($(this).index() != clickIdx) {
if(clickIdx >= 0) {
$thisObj.find("tbody tr:eq(" + clickIdx + ")").css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
$(this).css({
"background-color": cfg.clickBgColor,
"color": cfg.clickFgColor
});
clickIdx = $(this).index();
}
});
return this;
}
})($);
$(document).ready(function () {
$("#table1")
.szThreeStateColor({
"overBgColor": "#34ef2a",
"overFgColor": "#000000",
"clickBgColor": "#333333"
});
$("#table2").szThreeStateColor();
});
</script>
</HEAD>
<BODY>
<table id="table1" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table id="table2" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
This plugin sets different cell colors when the events mouseover, mouseout, click are fired. The plugin works fine with a single table but works abnormally when multiple tables are used. Maybe the variable clickIdx is shared by each table. How can I prevent sharing of that variable?

You can do so by wrapping your plugin in return this.each(function() {...}).
jQuery.fn.szThreeStateColor = function (settings) {
// ...
return this.each(function() {
// variables that need to be private go in here
});
}

Related

Sort table using jquery.ui and store the new position to database

I have a table named categories where I store the categories for an E-Commerce. This table has the following aspect:
And this is the user interface to admin the categories.
I want to make a system to sort this table using JQuery.UI.
This is what I tried, but it returns me 500 (Internal Server Error)
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
foreach($categories as $category)
<tr data-index="{{$category->id}}" data-position="{{$category->position}}">
<td class="table-text">{{$category->name}}</td>
<td class="table-text table-justified hide-mobile">
if ($category->visibility)
<i class="far fa-eye"></i>
else
<i class="far fa-eye-slash"></i>
endif
</td>
<td class="table-text table-opts">{{$category->position}}</td>
<td class="table-opts">
<div class="operations">
<a href="{{url('/admin/categories/'.$category->id.'/edit')}}" class="btn-edit pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
<i class="fas fa-edit"></i>
</a>
<a href="{{url('/admin/categories/'.$category->id.'/delete')}}" class="btn-delete btn-confirm pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
endforeach
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#table_content').sortable({
cancel: 'thead',
stop: () => {
var items = $('#table_content').sortable('toArray', {attribute: 'data-index'});
var ids = $.grep(items, (item) => item !== "");
$.post('{{ url('/admin/categories_list/reorder') }}', {
": $("meta[name='csrf-token']").attr("content"),
ids
})
.fail(function (response) {
alert('Error occured while sending reorder request');
location.reload();
});
}
});
});
</script>
And this is the controller function:
public function postCategoriesReorder(Request $request){
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
foreach ($request->ids as $index => $id){
DB::table('categories')->where('id', $id)->update(['position' => $index+1]);
}
return response(null, Response::HTTP_NO_CONTENT);
}
Consider the following example.
var tableData = [{
id: 1,
name: "Cat 1",
visibility: true,
position: 1
}, {
id: 2,
name: "Cat 2",
visibility: false,
position: 2
}, {
id: 3,
name: "Cat 3",
visibility: true,
position: 3
}, {
id: 4,
name: "Cat 4",
visibility: true,
position: 4
}, {
id: 5,
name: "Cat 5",
visibility: true,
position: 5
}];
$(function() {
function updateTable(data) {
$.each(data, function(i, r) {
var row = $("<tr>", {
"data-index": r.id
}).data("row", r).appendTo("#table_content");
$("<td>", {
class: "table-text"
}).html(r.name).appendTo(row);
$("<td>", {
class: "table-text table-justified hide-mobile"
}).html("<i class='fas fa-eye'></i>").appendTo(row);
if (!r.visibility) {
$(".fa-eye", row).toggleClass("fa-eye fa-eye-slash");
}
$("<td>", {
class: "table-text table-opts"
}).html(r.position).appendTo(row);
$("<td>", {
class: "table-opts"
}).appendTo(row);
$("<div>", {
class: "operations"
}).appendTo($("td:last", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/edit",
class: "btn-edit pV-8 pH-12",
title: "Editor",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-edit'></i>").appendTo($("td:last > div", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/delete",
class: "btn-delete btn-confirm pV-8 pH-12",
title: "Eliminar",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-trash-alt'></i>").appendTo($("td:last > div", row));
});
}
function gatherData(table) {
var rows = $("tbody > tr", table);
var item;
var results = [];
rows.each(function(i, el) {
item = $(el).data("row");
item.position = i + 1;
results.push(item);
});
return results;
}
updateTable(tableData);
$('#table_content').sortable({
cancel: 'thead',
start: (e, ui) => {
start = $('#table_content').sortable('toArray', {
attribute: 'data-index'
});
},
stop: () => {
ids = gatherData("table");
console.log(start, ids);
/*
$.post('/admin/categories_list/reorder', {
"csrf-token": $("meta[name = 'csrf-token']").attr("content"),
ids
})
.fail(function(response) {
alert('Error occured while sending reorder request');
location.reload();
});
*/
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" integrity="sha384-jLKHWM3JRmfMU0A5x5AkjWkw/EYfGUAGagvnfryNV3F9VqM98XiIH7VBGVoxVSc7" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
This should allow you to pass the new position for each ID to the script so the Database is updated.

Simple UI testing a button click with karma and qUnit

I have figured out how to test my code with the karma test runner, but I cannot figure out how to test the UI features on a web page.
I have a simple calculator program (calculator.js):
window.onload = function () {
var okResult = /^.*(\+|\*|-|÷)\d$|^\d$|^.*\d((\+|\*|-|÷)|\d)$/,
i, tds = document.getElementsByTagName("td");
var setResult = function (t) {
document.getElementsByTagName("th")[0].innerHTML = t;
};
var appendResult = function (t) {
document.getElementsByTagName("th")[0].innerHTML += t;
};
var getResult = function () {
return document.getElementsByTagName("th")[0].innerHTML;
};
for (i = 0; i < tds.length; i++) {
tds[i].onclick = function () {
var r;
if (this.innerHTML == '=') {
setResult(eval(getResult().replace(/÷+?/g, '/')));
} else if (this.innerHTML == 'clr') {
setResult("0");
} else if (getResult() == '0') {
setResult(this.innerHTML);
} else {
appendResult(this.innerHTML);
}
if (!okResult.test(getResult())) {
r = getResult();
setResult(r.substring(0, r.length - 1));
}
};
}
};
With this simple table in the HTML DOM (calculator/index.html):
<table>
<tr>
<th id="results" colspan="4">0</th>
</tr>
<tr>
<td colspan="3"> </td>
<td>clr</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>÷</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<td>*</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>-</td>
</tr>
<tr>
<td>.</td>
<td>0</td>
<td>=</td>
<td>+</td>
</tr>
</table>
I want to test it by triggering click events on the cells found in the DOM. For example (calculator-spec.js):
test("Calculator initially displays 0", function () {
equal( $('td#results').text(), "0", "Initial display is 0" );
});
test("Calculator can add numbers", function () {
$('td:contains("1")').trigger('click');
$('td:contains("+")').trigger('click');
$('td:contains("1")').trigger('click');
$('td:contains("=")').trigger('click');
equal( $('td#results').text(), "2", "Initial display is 0" );
});
I am trying to automate testing with karma, and in my karma.conf.js file I have:
// frameworks to use
frameworks: ['qunit'],
// list of files / patterns to load in the browser
files: [
'http://code.jquery.com/jquery-1.10.2.min.js',
'**/Examples/Calculator/Complete/calculator.js',
'test/calculator/calculator-spec.js',
{pattern: '**/Examples/Calculator/Complete/index.html', watched: false, included: false, served: true}
],
How do I perform UI testing using karma. How can I simulate mouse and keyboard events and check the resulting DOM using either qUnit or jasmine?
I've had to use the DOM elements click method:
$('td:contains("1")')[0].click();

Duplicated List of DropdownList when ajax update?

I have a Ajax Jquery function:
function UpdateValue() {
$(document.body).on("change",".quantity", function () {
var ProID = $(this).attr("data");
var Quantity = $(this).val();
$.ajax({
type: "GET", url: "/Cart/UpdateValue",
data: { ProID: ProID, quantity: Quantity },
success: function (data) {
$("#cartbox").html(data);
}
}
);
$.ajaxSetup({
cache: false
});
});
}
call UpdateValue in Cart Controller:
public PartialViewResult UpdateValue(Cart cart,int ProID, int quantity)
{
List<SelectListItem> items = new List<SelectListItem>();
for (int i = 1; i <= 10; i++)
{
items.Add(new SelectListItem { Text = i.ToString(),
Value = i.ToString() });
}
ViewBag.Items = items;
Product product = repository.Products.FirstOrDefault(p => p.ProductID
== ProID);
if (product != null)
{
cart.UpdateItem(product, quantity);
}
CartIndexViewModel ptview = new CartIndexViewModel { Cart = cart,
ReturnUrl = "/" };
return PartialView(ptview);
}
When the ajax function success, it returns UpdateValue View. But the Dropdown List always changes the same in each row. How can i pass the selected value from the Index View after ajax update?
Here is my UpdateValue View Code:
<table id="cartbox">
<thead>
<tr>
<th>Tên hàng</th>
<th>Số lượng</th>
<th>Đơn giá</th>
<th colspan="2" style="width:70px">Thành tiền</th>
</tr>
</thead>
<tbody>
#foreach (var line in Model.Cart.Lines)
{
<tr>
<td>#line.Product.Name
</td>
<td>#Html.DropDownList("Quantity", new SelectList(ViewBag.Items as System.Collections.IList, "Value", "Text", line.Quantity), new { data = line.Product.ProductID, #class = "quantity" })</td>
<td style="color:#3A9504;margin-left:3px">#string.Format("{0:00,0 VNĐ}", line.Product.Price)</td>
<td>#string.Format("{0:00,0 VNĐ}", (line.Quantity * line.Product.Price))</td>
<td align="center" style="width:10px"><img src="#Url.Content("~/Content/Images/delete.png")" style="padding-right:10px" /></td>
</tr>
}
</tbody>
<tfoot>
<tr style="border-top-style:solid;border-top-color:#DFDFDF;border-top-width:1px;">
<td colspan="3" align="right" style="border-right-color:#808080;border-right-style:solid;border-right-width:1px;text-align:right"><b>Tổng tiền:</b></td>
<td style="text-align: center"><b>#string.Format("{0:00,0 VNĐ}", Model.Cart.ComputeTotalValue())</b></td>
<td></td>
</tr>
</tfoot>
</table>
If I understand you correctly then your problem is that after updating the data in the dropdown list you lose the selection in that dropdown list?
If so then you would need to add this to your success handler in JavaScript:
success: function (data) {
$("#cartbox").html(data);
$("#cartbox").find(".quantity").val(Quantity);
}

Edit button in a view details popup in MVC 3 using jQuery

I am currently in the process of setting up an MVC entities page with the ability to list all entities of a certain type, using jQuery popups to create new entities, edit or delete existing entities.
As not all entities' details are shown in the list, I would like to provide a details view (read only) which has an edit button in case changes need to be made.
However, at the moment I have not been able to implement this and would welcome any suggestions on how to proceed. Please find the view definitions included below:
Entity Country:
/Views/Country/Index:
#model IEnumerable<MVCjQuerySample2.Entities.Country>
#{
ViewBag.Title = "Countries";
}
<h2>Countries</h2>
<span class="AddLink IconLink"><img src="/Content/Images/Create.png" alt="Add new country" /></span>
<div id="ListBlock"></div>
<div id="EditDialog" title="" class="Hidden"></div>
<div id="DeleteDialog" title="" class="Hidden"></div>
<script type="text/javascript">
$(function () {
$("#EditDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
if ($("#EditForm").validate().form()) {
$.post("/Country/Save", $("#EditForm").serialize(), function (data) {
$("#EditDialog").dialog("close");
$("#ListBlock").html(data);
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#DeleteDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Delete": function () {
$.post("/Country/Delete", $("#DeleteForm").serialize(), function (data) {
$("#DeleteDialog").dialog("close");
$("#ListBlock").html(data);
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".AddLink").click(function () {
$("#EditDialog").html("")
.dialog("option", "title", "Add new Country")
.load("/Country/Create", function () { $("#EditDialog").dialog("open"); });
});
$(".EditLink").live("click", function () {
var id = $(this).attr("itemid");
$("#EditDialog").html("")
.dialog("option", "title", "Edit Country")
.load("/Country/Edit/" + id, function () { $("#EditDialog").dialog("open"); });
});
$(".DeleteLink").live("click", function () {
var id = $(this).attr("itemid");
$("#DeleteDialog").html("")
.dialog("option", "title", "Delete Country")
.load("/Country/DeleteConfirm/" + id, function () { $("#DeleteDialog").dialog("open"); });
});
LoadList();
});
function LoadList() {
$("#ListBlock").load("/Country/List");
}
/Views/Country/List:#using MVCjQuerySample2.Helpers
#model IEnumerable<MVCjQuerySample2.Entities.Country>
<table class="CountryList">
<tr>
<th>Iso</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Iso)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<span class="EditLink IconLink" itemid="#item.Id"><img src="/Content/Images/Pencil.png" alt="Edit" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Pencil.png", "Edit", "Edit", new { id = item.Id })-->
</td>
<td>
<span class="DeleteLink IconLink" itemid="#item.Id"><img src="/Content/Images/Delete.png" alt="Delete" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Delete.png", "Delete", "Delete", new { id = item.Id })-->
</td>
</tr>
}
</table>
/Views/Country/EditForm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Save", "Country", FormMethod.Post, new { id = "EditForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("CreatedBy")
#Html.Hidden("CreatedOn")
#Html.Hidden("UpdatedBy")
#Html.Hidden("UpdatedOn")
<table>
<tr>
<td>Iso</td>
<td>#Html.TextBox("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBox("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
<script type="text/javascript">
$(function () {
$("#EditForm").validate({
rules: {
Iso: { required: true },
Name: { required: true }
}
});
});
/Views/Country/DeleteConfirm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Delete", "Country", FormMethod.Post, new { id = "DeleteForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("Iso")
#Html.Hidden("Name")
#Html.Hidden("CreatedOn")
#Html.Hidden("CreatedBy")
#Html.Hidden("UpdatedOn")
#Html.Hidden("UpdatedBy")
<table>
<tr>
<td>Iso</td>
<td>#Html.DisplayText("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.DisplayText("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}

JavaScript to get user input from editable table cell and send to server via json

I created a table with five columns dynamically. Two (the second and third column) of the five columns should be editable on the fly. Each time when user click on one the editable table cell, JavaScript should catch the user input and send the data to the server in json format. I have problem catch the user input and send to the server. Please help. This is my sample code -
<!DOCTYPE html>
<html>
<head>
<title>Editable table</title>
<style type="text/css" title="currentStyle">
#import "css/table.css";
</style>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
</head>
<body id="dt_example">
<div id="container">
<div class="full_width big">
Data table<br />
</div>
<div class="editab">
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>00123</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
<tr>
<td>00234</td>
<td onClick="editTableCell(this)">B20</td>
<td onClick="editTableCell(this)">$2,500.00</td>
<td>3.99 %</td>
<td>160</td>
</tr>
<tr>
<td>00345</td>
<td onClick="editTableCell(this)">C40</td>
<td onClick="editTableCell(this)">$3,500.00</td>
<td>3.99 %</td>
<td>180</td>
</tr>
<tr>
<td>00456</td>
<td onClick="editTableCell(this)">A20</td>
<td onClick="editTableCell(this)">$4,500.00</td>
<td>3.99 %</td>
<td>200</td>
</tr>
<tr>
<td>00567</td>
<td onClick="editTableCell(this)">B30</td>
<td onClick="editTableCell(this)">$5,500.00</td>
<td>3.99 %</td>
<td>225</td>
</tr>
<tr>
<td>00678</td>
<td onClick="editTableCell(this)">C10</td>
<td onClick="editTableCell(this)">$6,500.00</td>
<td>3.99 %</td>
<td>250</td>
</tr>
<tr>
<td>00789</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$7,500.00</td>
<td>3.99 %</td>
<td>300</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var SelectState = false;
var SelectedElement = null;
var TextInput = null;
var CellText = null;
var txt = "test";
var idcount = 0;
function editTableCell( e ){
if ( SelectState == false ){
SelectedElement = e;
CellText = e.innerHTML;
e.innerHTML = "";
var objInput = document.createElement("input");
objInput.type = 'text';
objInput.value = CellText;
objInput.id = "txt" + idcount++;
objInput.onkeypress = editTextBox;
objInput.size = 15;
TextInput = objInput;
e.appendChild(objInput);
SelectState = true;
} else if (e != SelectedElement) {
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
function editTextBox( e ){
if (navigator.appName == "Microsoft Internet Explorer"){
e = window.event;
key = e.keyCode;
}
else if (navigator.appName == "Netscape"){
key = e.which;
}
if ( key == 13 ){
SelectedElement.innerHTML = TextInput.value;
SelectState = false;
}
else if ( key == 27 ){
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
/* var attrName = "":
var attrValue = "";
if ($('#test1')
{
attrName= "editField01";
attrValue = $(#test1).val();
}
if ($('#test2')
{
attrName= "editField02";
attrValue = $(#test2).val();
}
if ($('#test3')
{
attrName= "editField03";
attrValue = $(#test3).val();
}
var values = '{"' + attrName + '":' + attrValue + '}';
$.ajax({
url: serverUrl + "/abc/contract/" + poolId,
async: false,
type: "PUT",
data: JSON.stringify(values),
dataType: 'json',
processData: false,
contentType: 'application/json',
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
error: function(err) {
alert("Failed to update the attribute");
htmlErrorDialog(err.responseText);
}
});*/
function showResponse(json) {
if(json.success){
// handle successful response here
alert("user input from column sent successfully!");
} else {
// handle unsuccessful response here
alert("user input fail to send. Please try again");
}
}
</script>
</body>
</html>
You're not actually passing the json data to showResponse:
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
Pass it along as so, and make sure that json is an actual object and that you don't need to parse it first:
success: function(json) {
// check that json is an actual object via an alert
// alert(json);
showResponse(json);
},
EDIT: Okay after a lot of working around, I have a simple test case for making the fields editable. Please note it uses jquery, and comments are inline:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!-- Date: 2011-05-10 -->
</head>
<body>
<form>
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<!-- The "identifier" class makes it so we have an id
to pass to our ajax script so we know what to change -->
<td class="identifier">00123</td>
<td class="editable">A30</td>
<td class="editable">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
// bind our event handler to all td elements with class editable
$('td.editable').bind('click', function() {
// Only create an editable input if one doesn't exist
if(!$(this).has('input').length) {
// Get the text from the cell containing the value
var value = $(this).html();
// Create a new input element with the value of the cell text
var input = $('<input/>', {
'type':'text',
'value':value,
// Give it an onchange handler so when the data is changed
// It will do the ajax call
change: function() {
var new_value = $(this).val();
// This finds the sibling td element with class identifier so we have
// an id to pass to the ajax call
var cell = $(this).parent();
// Get the position of the td cell...
var cell_index = $(this).parent().parent().children().index(cell);
// .. to find its corresponding header
var identifier = $('thead th:eq('+cell_index+')').html();
//ajax post with id and new value
$(this).replaceWith(new_value);
}
});
// Empty out the cell contents...
$(this).empty();
// ... and replace it with the input field that has the value populated
$(this).append(input);
}
});
</script>
</body>

Resources