Table with jQuery appendTo - javascript

I want to create table with these span and a href's. There must be just one tr and 3 td.
updater: function (selectedCustomer) {
valueAccessor()( parseInt(selectedCustomer.split('-')[0]));
if (valueAccessor()() > 0) {
$(element).hide();
var txt = $('<span>' + selectedCustomer + '</span>').appendTo($(element).parent());
var openCust = $('<i class="icon-search" style="font-size: 14pt; color: #000000;"></i>').appendTo($(element).parent());
var btn = $('<i class="icon-remove" style="font-size: 14pt; color: #000000;"></i>').appendTo($(element).parent());
btn.on("click", function () {
$(element).show();
txt.remove();
btn.remove();
openCust.remove();
valueAccessor()(0);
})
openCust.on("click", function () {
OpenCustomer(valueAccessor()());
})
}
// OpenCustomer(selectedCustomer);
}
});
I want to see my html like;
<table>
<tr>
<td><span>abc554444</span></td>
<td><a href>dsadasda</a> </td>
<td><a href>dsadasda</a> </td>
</tr>
</table>
How can I add table, tr, td tags to my code?
Thank you,

I tried to make it as simple example so that you can see how I first instantiate new elements, then manipulate, text, link etc.. and finaly I append it with jQuery ..
var ah = $('<a/>')
var sp = $('<span/>')
var td = $('<td/>')
var tr = $('<tr/>')
tr.append( td.clone().append( ah ).attr('href', '#').text('Link text') )
tr.append( td.clone().append( sp ).text('Lorem Ipsum') )
tr.append( td.clone().append( sp ).text('New Lorem Ipsum') )
var tb = $('<table/>').append(tr)
// append to body or some other element :)
$('body').append( tb )
http://codepen.io/mkdizajn/pen/BQgEWQ?editors=0110
hth, k

How I like to do it: create the different components ie span, a with hrefs etc. then append to
<table id="theTable">
<tr></tr>
</table>
var mySpan = "<span>What i want in it</span>";
var firstLink = "<a href='"+what ever i want here+"'>The other bits in here</a>";
var secondLink = "<a href='foo'>All the other stuff</a>";
$("body").on("click", ".myButton", function(){
$("#myTable tr").empty();
$("#theTable tr").append("<td>"+mySPan+"</td><td>"+firstLink+"</td><td>"+secondLink+"</td>");
});
The simple way usually works.

Related

How can i implement search like ctrl+f with jquery

Hi i am trying to search on page table tbody, the search is should be like ctrl + F search this my html and php code:
Please refer the image and link linked below for the sources.
<table>
<thead>
<tr><td><input type="text" placeholder="Search Student id="searchStudent"> </td>
<td></td><td></td><td></td><td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td>
<span><img src="<?php echo $gdScoreData['profile_pic']; ?>"/></span>
<p><?php echo $gdScoreData['student_fname'];?> <?php echo $gdScoreData['student_lname'];?></p>
<p><b>Hallticket</b> : S<?php echo $gdScoreData['student_pid']; ?>J<?php echo $jobID; ?></p>
</td>
<td></td><td></td><td></td><td></td><td></td></tr>
1st tr will close here php code is the above one in html it looks like shown in image:
<tr><td><span><img src="profile_pic/first_1479536519.jpg" width="50" /></span><p>Robert Smith</p><p><b>Hallticket</b> : S27J2</p></td></tr>
</tbody>
</table>
This my javascript code to search like ctrl + F
/* Search Student like ctrl+f start */
$("#searchStudent").on("keyup", function() {
var value = $(this).val();
console.log(value);
$("table tbody tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
/* Search Student like ctrl+f end*/
Here is the source from where i have tried:
Source JS
i have modified your js fiddle code now it working jsfiddle.net/rFGWZ/3406/
$("#search").on("keyup", function() {
var value = $(this).val();
if(value!='') {
$("table tbody tr").hide();
}else{
$("table tbody tr").show();
}
$('table tbody tr td:contains("'+value+'")').parent('tr').show();
});
Basically your code is working but it is not picking up elements inside your tag
try adding the following:
var id2 = $row.find("b:first").text();
and changing this:
if (id2.indexOf(value) !== 0) {
Then search based on the bold content and it should work
You could try it like this and search on each part individually:
$id = $row.find("td:first");
var id2 = $id.find("b:first").text();
var id3 = $id.find("p:first").text();
if (id2.indexOf(value) !== 0 && id3.indexOf(value) !== 0) {
$("#searchStudent").on("keyup", function() {
var value = $(this).val();
if(value!='') {
$("table tbody tr").hide();
}else{
$("table tbody tr").show();
}
$('table tbody tr td:contains("'+value+'")').parent('tr').show();
});
I have resolved with this help.

actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html

actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
Html Part:
<table id="ws-table" class="table table-bordered">
<tr id="insert">
<th>#</th>
<th>Date</th>
<th>Items</th>
<th>Edit / Delete</th>
</tr>
<!-- Here i wanted an tr
</table>
actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
javascript part :
var takeInput;
var DATA = [];
load();
function insertItem(){
takeInput = document.getElementById('item').value;
DATA.push(takeInput);
renderJson(DATA);
document.getElementById('item').value = "";
}
function renderJson(data){
document.getElementById('container').innerHTML = "";
for(var i in data){
container.innerHTML = container.innerHTML + "<div id=" + i + " onclick='removeItem(this.id)'><input type='checkbox'/><label>"+data[i]+"</label></div>";
}
save();
}
function removeItem(Id){
var itemId = document.getElementById(Id);
if(itemId.childNodes[0].checked == true){
var arr_ind = DATA.indexOf(itemId.childNodes[1].innerText);
DATA.splice(arr_ind,1);
itemId.parentNode.removeChild(itemId);
save();
}
}
function save(){
localStorage.myList = JSON.stringify(DATA);
}
function load(){
DATA = JSON.parse(localStorage.myList);
renderJson(DATA);
}
Element.innerHTML is for replacement only, so you need to read it first concatenate with new row and then assing back, better use Element.insertAdjacentHTML():
var row = "<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>";
document.querySelector("#ws-table tbody").insertAdjacentHTML("beforeend", row);
You may want to use thead for your table header. Check this thread for more information.

jQuery table loop?

I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});

How to put an onclick event for a HTML table row created dynamically through java script.?

I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.

Jquery Iterate over table and highlight cells that have changed

I have a table that is a history of a mysql record.
I want to add a button that will highlight the changes.
<table>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>
In this example the 600 would be highlighted as it was 300 and is now 600.
UPDATE: Thanks, I should have said there would be more than 2 rows. could be upto 20 rows
This jsFiddle shows an example that will iterate over a table of any size and highlight the cells that have changed from the previous row.
$(function() {
var $rows = $("tr");
for (oldIndex = 0; oldIndex < $rows.length-1; oldIndex++) {
var newIndex = oldIndex + 1;
var $oldCols = $("td", $rows[oldIndex]);
var $newCols = $("td", $rows[newIndex]);
for (col = 0; col < $oldCols.length; col++) {
var $newCol = $($newCols[col]);
if ($($oldCols[col]).html() != $newCol.html()) {
$newCol.addClass("highlight");
}
}
}
});​
Your solution should go along these lines. Assuming set1 and set2 are id's of two trs here is a sample code (not tested).
var s1 = $('tr#set1 td');
var s2 = $('tr#set2 td');
var l = $('tr#set1 td').length;
for(var i =0; i<l i++){
if(s1.eq(i).text() != s2.eq(i)){
$(s2.eq(i)).highlight();
}
}
$('table tr.new td').each(function(i){
//First TR td, Previous Rows
td = $(this);
check = $('table tr.prev td:eq('+i+')');
if(td[0].innerText != check[0].innerText)
{
check.addClass('Changed');
}
})​
This should do it but you need to add 2 classes:
<table>
<tr class="new">
<td>150</td>
<td>200</td>
<td>300</td>
</tr>
<tr class="prev">
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>​
Demo: http://jsfiddle.net/hjXZd/1/
Hope this helps.
I advise you to do an attr for each TD and place the mysql id in there so that you will only compare the rows that are the same in the DB, otherwise if your first list has more items then the second list the results will be corrupt.
Assuming your table has the id results, here is a solution:
var topRow = $('table#results tr:eq(0)');
var bottomRow = $('table#results tr:eq(1)');
topRow.find('td').each(function(index,item){
var shadow = bottomRow.find('td:eq('+index+')');
if($(item).contents().text()!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
Update: this solution compares the top row with all following ones:
$('table#results tr:eq(0) td').each(function(index,item){
var orig = $(item).contents().text();
$('table#results tr:gt(0)').find('td:eq('+index+')').each(function(index2,item2){
var shadow = $(item2);
if(orig!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
});
Using Jquery .live you can handle multiple elements.
See here
http://api.jquery.com/live/
You have to give ids for the changed values.. which can be inside divs.
Hope td also may work
On button click using this .live you can chnage style of div
like highlighting.
Use addClass function os jquery itslef or you can add css using jquery add

Categories

Resources