cloning and appending row in a table - javascript

How can I perform the following action using jquery?
I have a table with three rows and a header row. something like this:
When a user enters Data in "StudentId" field, "StudentFirstName" and "StudentLastName" are populated from database using jquery-Ajax. What I want to achieve is, Once a studentId is entered in first row textbox, I want to clone the first row and append it as second row and then clear the data from first row.
Hers is my Table structure:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Import Namespace="MyModel.Model" %>
<div>
<table id="MyTableHeaders">
<tr>
<th>
StudentId
</th>
<th>
StudentFirstName
</th>
<th>
StudentLastName
</th>
</tr>
</table>
</div>
<div>
<table id="MyTableData">
<tr>
<td>
<input name="StudentId"/>
</td>
<td>
<input name="StudentFirstName"/>
</td>
<td>
<input name="StudentLastName"/>
</td>
</tr>
</table>
</div>
Here is my jquery:
$('input[name="StudentId"]').focusout(function (e) {
e.preventDefault();
var link = '/Student/DisplayStudentDetails';
$.ajax({
type: 'POST',
url: link,
data: { id: $('input[name="StudentId"]').val() },
dataType: 'json',
success: function (result) {
$('input[name="StudentFirstName"]').val(result.FirstName);
$('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData tr:first").clone().appendTo("#MyTableData");
$("#MyTableData tr:first").find("input").attr("value", "").blur();
},
error: function (result) {
alert("Failed")
}
});
});
I am struggling with clearing data from first row and keeping data in the cloned row. With my code it clears all the rows.
Also, I noticed that cloned rows have the same field names, hence it will update all cloned "StudentFirstName" and "StudentLastName" fields with the studentId entered in first row. How should I approach this?
Any help would be appreciated.

success: function (result) {
var clone = $("#MyTableData tr:first").clone();
clone.find('input[name="StudentId"]').val(result.FirstName);
clone.find('input[name="StudentFirstName"]').val(result.FirstName);
clone.find('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData ").append(clone);
},
-edit-
although, when i've attempted tasks such as this in the past, i've created template rows.
a row that already exists but has display:none. that way if your table has no values you can always know the template row exists.
-edit-
if you want to add the new row at the begining, you can just use prepend instead of append.
or the second row would be $("#MyTableData tr").first().after(clone)

Related

Adding check boxes to allow multiple Delete & edit from my html table

I have the following table inside my asp.net mvc view:-
#foreach (var item in Model) {
<tr id="#item.TMSServerID">
<td>
#Html.ActionLink("Edit", "Edit","Server", new { id=item.TMSServerID },null) |
#if (!item.IsAlreadyAssigned()){
#Ajax.ActionLink("Delete",
"Delete", "Server",
new { id = item.TMSServerID },
new AjaxOptions
{ Confirm = "Are You sure You want to delete (" + item.Technology.Tag.ToString() + ")",
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})}
</td>
<td>
#Html.ActionLink(item.Technology.Tag,"Details","Server",new { id = item.TMSServerID},null)
</td>
<td class="hidden-phone" >
#item.status
</td>
The table allow edit,delete single item at a time. But now I want to do the following:-
Add a checkbox beside each row.
Add a Ajax delete button to delete selected items
Add a Transfer ajax button, which allow editing the selected items status.
So I am trying to achieve the following:-
How can I pass the item id + item timestamp field , using ajax button , as I need to check if the selected items has been modified by another user?
How I can remove the selected row from the html table incase the delete operation successed ?
Thanks
add a check box on each first cell of the table with ModelID as the value of each checkbox.
inside your foreach, include this:
<td>
<input type="checkbox" name="TMSServerID" value="1" />
</td>
add this into tha parameter of your controller: Int32[] idList, something like this:
public void CheckForIds(Int32[] idList)
{
//Manipulate idList
}
and in your button event, call the controller method.
You might want to take a look at this for your reference:
http://byatool.com/mvc/asp-net-mvc-how-to-handle-multiple-checkboxes-with-viewsactions-jquery-too/

change id attr's value using jquery

I have a table whose data is fetched from the database, and this table's each td's id is also dynamically unique ( td's id value is equal to database's table value ). In each td, when anyone double click on it, an input field is appeared, when the user edits an input field, I have made an Ajax call (using onblur), and update this td's field in the database. which will be worked I guess, Now I want to change that td's id value, which will come from database (Ajax call).
for example::
My table code ::
<td id="2*Name>Engr._C.F._Zaman" class=" "> Engr. C.F. Zaman </td>
this td's id is generated from database, where first 2 is id of the table's id, after (*) is the db table's column name [Name] and after (>) is the value of that column's whose id is 2
when anyone click on this td, he/she will get an input field just like as given below::
<td id="2*Name>Engr._C.F._Zaman" class=" ">
<input type="text" class="form-control" id="sabbir" value="Engr._C.F._Zaman" name="Name" onblur="AjaxChange('2', 'Name', 'Engr._C.F._Zaman', '2*Name>Engr._C.F._Zaman');">
</td>
this is generated using jquery onclick event.
Now if any change of above input field, AjaxChange is called. and my AjaxChange code is ::
function AjaxChange( id, Attr, tdValue, td ) {
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
// first I want to change the id of td, which value will be data
// td's id format is id*Attr>data
// next show data in the td with out input field
// <td id="id*Attr>data"> data </td>
}
});
}
Now How can I change this td's id attribute?
Solution to immediate problem.
<td id="2*Name>Engr._C.F._Zaman" class=" ">
<input type="text" class="form-control" id="sabbir"
value="Engr._C.F._Zaman"
name="Name"
onblur="AjaxChange('2', 'Name', 'Engr._C.F._Zaman', '2*Name>Engr._C.F._Zaman', this);">
</td>
Script function
function AjaxChange( id, Attr, tdValue, td, element ) {
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
//Set ID
$(element).closest("td").prop('id', YourNewID)
}
});
}
However, I would strongly recommend you to refactor your code and use data-* attribute. Heres example
HTML
<td class="" data-value="2*Name>Engr._C.F._Zaman" data-id="2" data-attr="Name" data-name="Engr._C.F._Zaman" >
<input type="text" class="form-control name-txt"
value="Engr._C.F._Zaman"
name="Name">
</td>
JavaScript
$('.name-txt').on('blur', function(){
var self = $(this);
var cell = self.closest("td");
var id = cell.data('id');
var Attr= cell.data('Attr');
var name= cell.data('name');
var tdValue = cell.data('value');
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
//Update values using
cell.data('id', YourNewID)
}
});
})
I suppose you meant using javascript/jquery, meaning the easiest way to reach the id would be using jqueries "attr"-function.
Now the question is what selector you should use, I guess in this case that your input fields id ("sabbir") is sufficient enough. You will have to decide this on your own.
$("#sabbir").closest("td").attr("id", yourNewId);
As answer to the other question in your comment:
$("#"+yourNewId).html(data);
Should work to replace the tds HTML.
your's ID 2*Name>Engr._C.F._Zaman which come from Database, is bad. Because special char is not always give result what you want, you should avoid this special char. You can use data-* to store your Database information then you don't have to change your ID every time.

Making a pre-populated form a HTML table in jquery

I am trying to create a prepopulated form that pulls values from any selected row in a HTML table . The HTML page is populated by a JSP .
my table looks like this
<table id="data-table" id="test">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>value4</th>
</tr>
</thead>
<tbody>
<tr>
<td id="class1"><%= value.valueOne() %></td>
<td id="class2"><%= value.valueTwo() %></td>
<td id="class3"><%= value.valueThree() %></td>
<td id="class4"><%= value.valueFour() %></td>
</tr>
<%
}
%>
</tbody>
</table>
I want to obtain a prepopulated form with the row values on click of a particular row . I have some js code that does this .
$(document).on("click", ".data-table .class1", function(e) {
var value = $(this).closest('tr').val();
console.log(value);
// Just to check if I get the correct value
});
unfortunately I cannot understand how to get the values for that particular row from the DOM and populate it in a form , That I want to overlay over the table . I would appreciate any pointers . I really would have written more code but I dnt know Jquery and am stuck
Your general strategy should be this:
Populate the table on the server side: done
Have the form pre-existing in the page, but hidden with css (display:none)
Register a click listener on all tr elements to:
find the values inside each td within the tr
select the corresponding form inputs
populate the inputs using jQuery's val(value) function.
unhide the form if it's hidden
With this in mind, I would change your click listener from document to something like this. (Note: I'm assuming value.valueOne() are just numbers or strings, and don't contain any html.
//target just TR elements
$('tr').click(function(){
values = [];
$(this).children().each(function(){
//add contents to the value array.
values.push($(this).html())
});
//fill in the form values
populateForm(values);
});
Populate form would completely depend on your form's HTML, but to get you started here's an idea of what it might look like:
function populateForm(values){
//set the value of the input with id of name to the value in the first td.
$('#name').val(values[0]);
//show the form (id inputForm) now that it's populated
$('#inputForm').show();
}
A couple things are wrong with your html markup and your JQuery selector. You'll never be able to execute the code you've provided...
You have two 'id' parameters in this element, <table id="data-table" id="test">... This will work with the JQuery I've fixed below, but it's malformed html either way.
In your selector, you are using the syntax for finding an element based on it's css class attribute, however your elements in your HTML have those values set as 'id' attributes. Thus, this, $(document).on("click", ".data-table .class1", function(e) {... should be written as follows, $(document).on("click", "#data-table #class1", function(e) {
Now, if you are attempting to get the values within all of the 'td' elements within a row, then all you really need to do is get the parent element of the 'td' that was clicked, and then get it's children. Then, for each child, get their values.
Like this...
$(document).on("click", "#data-table #class1", function(e) {
var elements = $(this).parent().children();
$.each(elements, function(index, el){
alert($(el).html());
});
});
I've saved a JSFiddle for you to see this in action... http://jsfiddle.net/2LjQM/
val() is used to return value of form inputs. You are using it to try to get the value of a row and row has no value.
Without seeing what your output into the TD as html, I assume it is a form control
Try
$(document).on("click", ".data-table .class1", function(e) {
var value = $(this).find(':input').val(); // `:input pseudo selector wull access any form control input,select,textarea
console.log(value);
// Just to check if I get the correct value
});
EDIT: if the TD contains text
var value = $(this).text();
Instead of scraping the DOM, you could invert the logic, and build the rows using javascript instead. Check out this jsBin to see the solution in action: http://jsbin.com/aligaZi/2/edit?js,output
Start with an empty table:
<table class="data-table" id="test">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>value4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Since you need to fill a form with the data, I'll be using a simple one as an example:
<form class="data-form">
<label>Value1<input class="value1" /></label>
<label>Value2<input class="value2" /></label>
<label>Value3<input class="value3" /></label>
<label>Value4<input class="value4" /></label>
</form>
Then, on the javascript side:
$(function() {
// Interpolate the values somehow.
// I'm not familiar with JSP syntax, but it shouldn't be too hard.
// I will use dummy data instead.
var tableData = [
{
value1: "row1-v1",
value2: "row1-v2",
value3: "row1-v3",
value4: "row1-v4"
}, {
value1: "row2-v1",
value2: "row2-v2",
value3: "row2-v3",
value4: "row2-v4"
}
];
// For each object, create an HTML row
var rows = $.map(tableData, function(rowData) {
var row = $("<tr></tr>");
row.append($('<td class="class1"></td>').html(rowData.value1));
row.append($('<td class="class2"></td>').html(rowData.value2));
row.append($('<td class="class3"></td>').html(rowData.value3));
row.append($('<td class="class4"></td>').html(rowData.value4));
// When this row is clicked, the form must be filled with this object's data
row.on("click", function() {
fillForm(rowData);
});
return row;
});
$(".data-table").append(rows);
function fillForm(rowData) {
var form = $(".data-form");
form.find("input.value1").val(rowData.value1);
form.find("input.value2").val(rowData.value2);
form.find("input.value3").val(rowData.value3);
form.find("input.value4").val(rowData.value4);
}
});

Check if values in checked row are equivalent

My application allows you to track orders in a store database. This database contains a weak entity used for notes which is attached to an orderID. I want to allow users to be able to apply to same 'note' to many orders at the same time, but there are some fields in the notes table that are dependent on the location of the sale. In other words, you should only be allowed to apply the same note if all the sale locations are the same.
Simplified View:
#using (Html.BeginForm("Create", "Note", FormMethod.Get, new { name = "editForm" }))
{
<table id="DataTable">
<tr>
<th>
<input type="button" value="Edit" onclick="checkboxValidation()"/>
</th>
<th>
#Html.DisplayNameFor(model => model.OrderID)
</th>
<th>
#Html.DisplayNameFor(model => model.location)
</th>
</tr>
#foreach (var item in Model)
{
<tr >
<td>
<input type="checkbox" name="ids" value="#item.orderID" />
</td>
<td>
#Html.ActionLink(item.OrderID.ToString(), "Details", "Search", new { orderID = item.orderID.ToString() }, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.location)
</td>
</tr>
}
</table>
checkboxValidation() is a javascript function I wrote to check if at least 1 checkbox is checked. How would I add a check to make sure all of the locations on checked lines are the same? Is this even possible? Thanks
EDIT: I missed a detail. When clicking the edit button, if the check is successful, it submits the form, which brings up the notes editor.
Should be fairly straightforward using JQuery:
// find all the checked rows
var checkedItems = $("#DataTable").find("tr td input[type=checkbox]");
// construct a locations array for all checked items
var locations = [];
checkedItems.each(function(index, element) {
if ($(element).is(":checked")) {
locations.push($(this).closest("td").next("td").next("td").text().trim());
}
});
// confirm each location is the same
var valid = true;
locations.each(function(index, element) {
if (index > 0 && locations[index-1] != element) {
valid = false;
return;
}
});
One additional thing you might want to do, is add some data tags to your tr and td elements, so that you can write more robust selectors that won't break with a minor UI re-arrangement (like tr[data-role=check] and tr[data-role=location], etc).
(Using JQuery closest and and JQuery each.)

pass var to function() js with jquery

Just looking for the best practise way of doing this.
I have a table listing information and in the last column is a button with "Edit/View". When the user clicks on the button a div area appears with more information which can be edited
Code below with some fragments of jstl
<script type="text/javascript">
//Click on Edit/View on table
$('.viewCustomer').click(function()
{
.......
});
</script>
<tr class="odd">
<td>${customerBean.comName}</td>
<td>${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
So my question would be:
(1) how do i pass a variable to function $('.viewCustomer').click(function()
(2) is this the best way of going about to do this. Is there a more efficient/secure/cleaner of doing this?
Cheers
Alexis
The click function will not be called by you. It is called when the button is clicked, and as such has the event object passed to it:
$('.viewCustomer').click(function(evt){
.......
});
What exactly are you wanting to pass? You can access the DOM element that you are clicking using this and $(this), so maybe it possible to reference what you want from here.
EDIT For comment
if the user clicked on the button that
was in the 4th row of the table and in
that row the another colum had
customer id 1234 i want to pass the
variable 1234.
NOTE: None of the below has been tested, but ought to suffice
Let's assume your 'customer id' column has a classname of 'customerid'. So your HTML might be:
<tr class="odd">
<td>${customerBean.comName}</td>
<td class="customerid">${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
The jQuery might look something like:
$('.viewCustomer').click(function(){
var $buttonCell = $(this).parent(); //the <td> containing the button
var $buttonRow = $buttonCell.parent(); //the <tr> containing the button and your customer id
var $customerIdCell = $buttonRow.find("td.customerid");
var customerId = $customerIdCell.text();
});
The above is proken down into lines to show you how stuff is being retrieved. Using 'chaining' we can express it more concisely:
$('.viewCustomer').click(function(){
var customerId = $(this).parent().parent().find("td.customerid").text();
}
You can also search for the customerid cell as a 'sibling' of the button cell for an even more concise approach (and one less function call).
$('.viewCustomer').click(function(){
var customerId = $(this).parent().siblings("td.customerid").text();
}

Categories