i am new to mvc and jquery,
i have created one table with jquery but i don't know how we add one actionlink in each row and also i need to call one function on the onclick event.
my code is given bellow
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td>' + '#Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
tab.append(trow);
});
here i got one error
"val is not in the current context"
please anyone help me to add one actionlink with click event.
You can achieve this by changing your code as below.
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td></td>');
tab.append(trow);
});
Try this and let me know, if you required anymore information.
Below Code Work Perfectly and Bind Table dynamically with Control.
function bindTable (data)
{
usersTable = $('<table><thead><tr>'
+ '<th style="width: 300px;">Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th>'
+ '</tr></thead ></table>').attr({ class: ["dataTable row-border hover"].join(' '), id: "table", style: "border: 1px solid; background-color:#d2d2d2;" });
var rows = new Number("10");
var cols = new Number("4");
var tr = [];
if (data != null) {
for (var i = 0; i < data.length; i++) {
var row = $("<tr></tr>").attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(table);
$("<td></td>").html(data[i].Col1).appendTo(row);
$("<td></td>").html(data[i].Col2).appendTo(row);
$("<td></td>").html(data[i].Col3).appendTo(row);
$("<td></td>").html(data[i].Col4).appendTo(row);
$("<td></td>").html($('<a href=/ControllerName/Action?ParamId='+data[i].Id+'>Action</a>')).appendTo(row);
}
}
table.appendTo("#Div");
$("#table").DataTable({
"aoColumns": [null, null, null, null, { "bSortable": false }]
});
}
Related
This is creating my table and working - It creates a table and I am going to have it check a list to hide columns. For testing purposes I am trying to hide the colun "Proj_Type" it does hide the header but does not hide the actual column of data. I want the entire thing to hide.
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table/>', {
'class': 'GRD1',
id: id + "GRDMKTLIST",
}
)
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
if (colHeader[i] != "notes") {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
if (colHeader[j] != "notes") {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$($table.find('th')).each(function () {
var indextest = $(this).index() + 1;
if ($(this).text() == "Proj_Type") {
$('[id*=GRDMKTLIST] td:nth-child(' + indextest + '),th:nth-child(' + indextest + ')').hide();
}
})
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
However, on the bottom where i have
if ($(this).text() == "Proj_Type") {
$('[id*=GRDMKTLIST] td:nth-child(' + indextest + '),th:nth-child(' + indextest + ')').hide();
}
This only hides the header and I am trying to hide the entire column TD included.
There are two main issues:
$('[id*=GRDMKTLIST]
will look in the DOM, but your $table has not yet been added to the DOM, so does nothing. Use $table.find(... to use the $table variable in memory.
$tbody.append('<td
will append the td (and equivalent code for th) to the tbody - but these should be in a tr.
The browser will do some "magic" and see an empty <tr></tr> and put a new row in for you, but selectors for tbody > tr > td won't work. This also means there's only a single :nth-child(n) per n, not per row (as all cells across all rows are siblings).
You can add a new row to $tbody and return the new row by using .appendTo
$tr = $("<tr>").appendTo($tbody);
then add the th/td to $tr and not $tbody
$tr.append('<td...`
Regarding the selector for $table.find("td,th") you don't need the th part as you're looping th and it's already this, so you can do:
$(this).hide();
$table.find('td:nth-child(' + indextest + ')').hide();
Also make sure you only create tr as you need it. Your code create a tr before the data row loop and inside the data row loop, leaving an empty tr.
for (var i = 0; i < data.length; i++) {
$tr = $("<tr>").appendTo($tbody);
for (var j = 0; j < colHeader.length; j++) {
if (colHeader[j] != "notes") {
$tr.append('<td id=' + colHeader[j] + '>' + data[i][colHeader[j]] + '</td>');
}
}
}
Also updated in the fiddle: https://jsfiddle.net/n168ra2g/3/
I have JSON data like this:
[0:{name:"jason",height:"150cm"},
1:{name:"henry",height:"178cm"}]
I'm trying to do a for loop in my function, which is
function DrawTable(output) {
var general = output;
var sb = new StringBuilder();
for (var i = 0; i < *total row in the json*; i++)
sb.append("<td>" + general[0][i]["name"] + "</td>");
sb.append("<td>" + general[0][i]["height"] + "</td>");
}
I don't know the way to do it..
First off: that data isn't JSON.
For the sake of argument, let's pretend it was formatted as such:
[{
"name": "jason",
"height": "150cm"
}, {
"name": "henry",
"height": "178cm"
}]
Which would be valid JSON.
You could then do something more like this:
If using jQuery:
function DrawTable(jsonString) {
var stuff = JSON.parse(jsonString);
var table = createElement('table')
.append(
createElement('thead')
.append(
createElement('tr')
.append(
createElement('th').text('Name'),
createElement('th').text('Height')
)
)
);
var body = createElement('tbody');
stuff.forEach(function(item) {
body
.append(
createElement('tr')
.append(
createElement('td').text(item.name),
createElement('td').text(item.height)
)
);
});
//append body to table and show on page somewhere
}
Or, based on your existing code:
function DrawTable(output) {
var general = JSON.parse(output);
var sb = new StringBuilder();
for (var i = 0; i < general.length; i++) {
sb.append("<td>" + general[i].name + "</td>");
sb.append("<td>" + general[i].height + "</td>");
}
}
If your data happens to be formatted like:
{
0: {name:"jason",height:"150cm"},
1: {name:"henry",height:"178cm"}
}
instead of wrapped in an array. Then looping through Objects.values(yourData) might be what you are looking for:
function DrawTable(objectsData) {
var htmlString = '';
Object.values(objectsData).forEach((object) => {
htmlString += "<td>" + object.name + "</td>";
htmlString += "<td>" + object.height + "</td>";
});
return htmlString;
}
In this table, I want to select multiple cells as a group.
You can select a target cell by clicking on it,
but I also want to click and drag to cover multiple cells as a group.
Is that possible to achieve that without any plugins (just use JQuery)?
This is what I want to achieve:
The array content will be:
["3-2", "3-3", "4-2", "4-3", "5-2", "5-3"]
Here is what I try so far:
var group = [];
var columnIndex = 7,
rowIndex = 10;
var $tableContainer = $('#tablecontainer'),
$table = $tableContainer.append('<table border="1" id="table1"></table>'),
$thead = $table.find('table').append('<thead></thead>'),
$tbody = $table.find('table').append('<tbody></tbody>');
var $columnNumber = "";
var $tdNumber = "";
for (var col = 1; col <= columnIndex; col++) {
$columnNumber += "<th>Column " + col + "</th>";
$tdNumber += "<td style='text-align: center; vertical-align: middle; color:red'></td>";
}
$thead = $thead.append('<tr><th>0</th>' + $columnNumber + '</tr>');
for (var row = 1; row <= rowIndex; row++) {
$tbody = $tbody.append('<tr><td>Row ' + row + '</td>' + $tdNumber + '</tr>');
}
$('#table1 > tbody > tr > td').hover(function() {
var colIndex = $(this).parent().children().index($(this));
var rowIndex = $(this).parent().parent().children().index($(this).parent());
$(this).attr("title", 'Row: ' + rowIndex + ', Column: ' + colIndex);
// console.log('Row: ' + rowIndex + ', Column: ' + colIndex);
});
$('#table1 > tbody > tr > td').click(function() {
var colIndex = $(this).parent().children().index($(this));
var rowIndex = $(this).parent().parent().children().index($(this).parent());
group.push(rowIndex + "-" + colIndex);
console.log(group);
$(this).css("background-color", "red");
// console.log('Row: ' + rowIndex + ', Column: ' + colIndex);
});
#table1>tbody>tr>td:hover {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tablecontainer"></div>
Any help would be appreciated!
The functionality you want to achieve is possible by using jquery mouseover function.
I made a fiddle to get the desired output as you expect.
Fiddle
Hope this helps you in solving the issue.
-Help :)
I want to create HTML table in java script. Inside a for loop I want to create a dynamic table which can be extended. This is how I am it using now:
function(json)
{
var content= $('#name1').html('').append('<td> Name: ' + json.name + '<td>');
var content= $('#address1').html('').append('<td> address: ' + json.address + '<td>');
var content= $('#age1').html('').append('<td> age: ' + json.age + '<td>');
var content= $('#status1').html('').append('<td> status: ' + json.status + '<td>');
}
HTML file is
<table>
<tr id="name1"></tr>
<tr id="address1"></tr>
<tr id="age1"></tr>
<tr id="status1"></tr>
</table>
now it is just with hardcore values but I want it auto generated and insert more rows if neccessary...
remove id from tr. Because if you need multiple row then id will be duplicated which is not valid.
<table id="mytable">
</table>
function(json)
{
for(i=0;i<json.length;i++){
var newRow= $("<tr></tr>");
newRow.append('<td> Name: ' + json[i].name + '<td>');
newRow.append('<td> address: ' + json[i].address + '<td>');
newRow.append('<td> age: ' + json[i].age + '<td>');
newRow.append('<td> status: ' + json[i].status + '<td>');
$("#mytable").append(newRow);
}
}
i think this will help you
function(json)
{
for(i=0;i<jsn.length;i++){
$('#YOUR_TABLE_ID').append("<tr><td>"+ json.name+"</td></tr>")
}
}
<table id="mytable">
<tr id="name1"><td></td></tr>
</table>
if (results != null && results.length > 0) {
// Build our table header
var content = "";
for(i=0;i<data.length;i++)
{
content += '<tr>';
content += '<td></td>'
}
content += '</tr>';
}
$("#mytable tbody").append(content);
}
You can Use Append Method to create Rows in a table like
for(i=0;i<data.length;i++)
{
$("YOUR_TABLE_ID").append("<tr><td>"+data[i]['name']+"</td><td>"+data[i]['address']+"</td><td>"+data[i]['age']+"</td><td>"+data[i]['status']+"</td></tr>");
}
I'm not clear with your requirement but i can provide you some basic code hope that helps you.
var jsonList = [{name:'Jhon',address:'Jhon Address goes here',age:'27',status:'Single'},
{name:'Smith',address:'Smith Address goes here' ,age:'32', status:'Single' }];
function createTable(){
var table = '<table>';
for(var ind=0;ind< jsonList.length;ind++)
table += fetchRowInformation(jsonList[ind]);
console.log(table+'</table>');
}
function fetchRowInformation(json){
return '<tr><td> Name: ' + json.name + '<td>'+'<td> address: ' + json.address + '<td>'+ '<td> age: ' + json.age + '<td>'+'<td> status: ' + json.status + '<td></tr>';
}
JS Fiddle Demo
function tableCreate(rows, columns) {
var body = document.body
tbl = document.createElement('table');
tbl.style.width = '20%';
tbl.style.border = '1px solid black';
for (var i = 0; i < rows; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < columns; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode('Cell'));
td.style.border = '1px solid black';
}
}
tbl.style.marginTop = '10px'
tbl.style.borderCollapse = 'collapse'
td.style.padding = '2px'
body.appendChild(tbl);
}
tableCreate(15, 10);
I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE