plain text to input text on click using javascript - javascript

I have a table that needs edit buttons in each row, on click the plain text should become input, I've read many tutorial but i understand none as i am new to javascript, can anyone help?
this is what i started with:
<script type="text/javascript">
function Edit(clickedButton){
//get row of the clicked button
var row = clickedButton.closest('tr');
'retrieve each info
var tdID = row.cells[0];
var tdFirstName = row.cells[1];
var tdLastName = row.cells[2];
var tdDOB = row.cells[3];
var tdGender = row.cells[4];
var tdStatud = row.cells[5];
</script>
and this in my table:
<table id="table" class="table .table-bordered" style="width:80%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr id="frow">
<td>1</td>
<td>Samir</td>
<td>Khattar</td>
<td>1-12-1990</td>
<td>Male</td>
<td>Married</td>
<td>
<button onclick="Edit(this)">Edit</button>
<button onclick="Delete(this)">Delete</button>
</td>
</tr>
</tbody>
</table>
and whats the difference between .innerhtml and .html

At first take a form to get input as you want. Then hide the input area as default. And show As you are showing your table inside the form. If any of the button is clicked then the hidden input area will be shown and the the default table row will be hidden. This is the idea to do so.
innserHTML is a javascript DOM property. It return DOM's inner html, it can also be used as to change the inner html of that dom. On the other hand, html() is a jQuery library function to do the same work. May be this method of jQuery actually use the innserHTML property.
To know about the performance of innerHTML and & html() you can check out this link: .append VS .html VS .innerHTML performance
Best of luck

Simply do like this...it will work...
$(function () {
$("#table td").click(function (e) {
e.preventDefault(); // <-- consume event
e.stopImmediatePropagation();
$this = $(this);
if ($this.data('editing')) return;
var val = $this.text();
$this.empty()
$this.data('editing', true);
$('<input type="text" class="editfield">').val(val).appendTo($this);
});
putOldValueBack = function () {
$("#table .editfield").each(function(){
$this = $(this);
var val = $this.val();
var td = $this.closest('td');
td.empty().html(val).data('editing', false);
});
}
$(document).click(function (e) {
putOldValueBack();
});
});
//Refer this example
<table id="table">
<tr>
<th>RecID</th>
<th>Col1</th>
<th>Col2</th>
</tr>
<tr>
<td>RecID</td>
<td>Val1.1</td>
<td>Val1.2</td>
</tr>
<tr>
<td>RecID</td>
<td>Val2.1</td>
<td>Val2.2</td>
</tr>
<tr>
<td>RecID</td>
<td>Val3.1</td>
<td>Val3.2</td>
</tr>
</table>

Try this
function Edit(clickedButton){
var getTR = clickedButton.parentNode.parentNode;
var getLength = getTR.childElementCount;
var getTds = getTR.querySelectorAll("td")
for (i in getTds){
if(i < (getLength-1)){
getTds[i].innerHTML = "<input type='text' value='"+getTds[i].innerHTML+"'>";
}
}
}

Related

Button to remove row of table is not working using Javascript

This is the table in which I have used button to remove of table.
<table>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>User Name</th>
<th>Email</th>
<th>Remove</th>
</tr>
<tr>
<td>Sujan6</td>
<td>Bikram5</td>
<td>Thapa</td>
<td>Sujan6</td>
<td>Sujan#gmail5</td>
<td><button class="button button3">Remove</button></td>
</tr>
<tr>
<td>Sujan7</td>
<td>Bikram6</td>
<td>Thapa</td>
<td>Sujan7</td>
<td>Sujan#gmail5</td>
<td><button class="button button3">Remove</button></td>
</tr>
</table>
This is the Javascript code with which I am trying to remove row of table. This code show error of:
"TypeError: Cannot read property 'parentNode' of undefined" at the line of " var tr = td.target.parentElement;"
var deleteRecord = document.getElementsByClassName('button button3');
for (var i = 0; i < deleteRecord.length; i++) {
deleteRecord[i].addEventListener('click', removeItem);
}
function removeItem(e) {
event.preventDefault();
if (confirm('Are You Sure')) {
var td = e.target.parentElement;
var tr = td.target.parentElement;
tr.parentElement.removeChild('tr');
}
}
td is not an event, so it doesn't have a target. Accessing this will cause the error you are seeing. Access the parentElement directly on td.
You also need to remove the quotes around tr when removing the element.
function removeItem(e) {
event.preventDefault();
if (confirm('Are You Sure')) {
var td = e.target.parentElement;
var tr = td.parentElement;
tr.parentElement.removeChild(tr);
}
}

How to find the corresponding th to a given td?

Basically the same question as How can I get the corresponding table header (th) from a table cell (td)? but not jQuery specific.
From a given <td> is there an easy way to find the corresponding <th>?
<table width="100%" id="stock">
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
I'd like something doing this:
document.getElementById('target').correspondingTH // would return HTMLObject <th>Type</th>
An ideal answer might contain both a jQuery way to do it and a vanilla one but I'm personally looking for a vanilla one.
Pure JavaScript's answer.
var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
As posted here in the more jQuery specifc question: https://stackoverflow.com/a/37312707/1524913
HTML table model gives easier solution. jquery in this case is more sophisticated. I tested following table:
<table style="width:100%" id="stock">
<tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
</tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td colspan="2">-1</td>
<!--<td>...</td>-->
</tr>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
</thead>
</table>
Script without jquery is simple and straightforward.
window.onload = function () {
var tbl = document.getElementById('stock');
var tds = document.getElementsByTagName('td');
for (var i = 0, td; td = tds[i]; ++i) {
td.onclick = function () {
var tr = this.parentNode;
console.log(tbl.rows[0].cells[this.cellIndex].innerHTML);
}
}
}
jquery also is useful.
$(document).ready(function () {
$('#stock td').click(function () {
console.log($(this).parents('table').find('tr:first-child').children('th:nth-child(' + (this.cellIndex + 1) + ')').html());
});
});
<thead> can be placed at the top, at the bottom, and between rows. thead inside tbody is obvious error but browser fixes it. Scripts work in any case.
I think you need to step through the TH colSpans to exactly match the TD
Try
function getHeadCell(td) {
var index = Array.prototype.indexOf.call(td.parentNode.children, td);
var table = td;
while (table && table.tagName != 'TABLE') table = table.parentNode;
var cx = 0;
for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;
return table.rows[0].cells[c - 1];
}
See https://jsfiddle.net/Abeeee/upt75s2x/34/ for a working example

Jquery how to get attr tag value

I need the value in 'c_name' for the row I clicked on. Why is this not working? What's the correct syntax argggg
http://jsfiddle.net/UW38e/400/
Heading
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td c_name="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<button type="button" class="use-address">get value </button>
</td>
</tr>
</tbody>
</table>
From table syntax
$("#choose-address-table").click(function() {
var $row = $(this).attr("c_name"); // Find the text
var $row = $(this).find(["c_name"]);
// Let's test it out
alert($row);
});
#choose-address-table does not have an attribute named c_name.
It however has a cell with that attribute.
From you fiddle you can use the attribute selector to select the cell you need to get the value
$(".use-address").click(function() {
var $row = $(this).closest("tr"); // Find the row
var $text = $row.find("[c_name]").text(); // Find the text
// Let's test it out
alert($text);
});
http://jsfiddle.net/UW38e/406/
From the table point of view
$("#choose-address-table").click(function(e) {
if ($(e.target).is(".use-address")){// button clicked
var $row = $(e.target).closest("tr"); // Find the row
var $text = $row.find("[c_name]").text(); // Find the text
// Let's test it out
alert($text);
}
});
http://jsfiddle.net/UW38e/407/
You're wanting, I believe, to find the row, and then find the td that has a c_name attribute, and then get the text inside that td or inside the span inside that td. Use:
var $row = $(this).closest('tr');
var c_nameText = $($row).find('td[c_name]').text(); // Find the text
JSFiddle here.

Highlight repeating strings

I have up to three almost-identical divs that contain tables of usernames. Some names may be repeated across the three divs. I'd like to highlight the names that are repeated. The first occurrence of the user should not be colored, the second occurrence should have an orange background and the third should have a red background. The divs go from left to right in order so the first div should not have any highlighted usernames.
My HTML looks like:
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th>2/26/2014</th>
</tr>
<tr>
<td>user1</td>
</tr>
<tr>
<td>user2</td>
</tr>
<tr>
<td>user5</td>
</tr>
<tr>
<td>user17</td>
</tr>
</table>
</div>
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th>2/27/2014</th>
</tr>
<tr>
<td>user13</td>
</tr>
<tr>
<td>user5</td>
</tr>
<tr>
<td>user7</td>
</tr>
</table>
</div>
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th>2/28/2014</th>
</tr>
<tr>
<td>user5</td>
</tr>
<tr>
<td>user45</td>
</tr>
<tr>
<td>user1</td>
</tr>
</table>
</div>
I know that the username table cells will be selected with $('table.table td') (if I use jQuery) but I'm not sure what to do from there.
Please let me know if you have any questions.
Thank you.
Is this what you want?
I created a map to store text-occurrence pairs. Each time the text is repeated, the counter associated with it gets incremented. If the counter climbs to a certain value, the background will be set to another color. Give it a shot!
DEMO
var map = new Object();
$('td').each(function() {
var prop = $(this).text()
var bgColor = '#FFFFFF';
if (map[prop] > 1) {
bgColor = '#FF0000';
} else if (map[prop] > 0) {
bgColor = '#FF7F00';
}
$(this).css('background', bgColor);
if (map.hasOwnProperty(prop)) {
map[prop]++;
} else {
map[prop] = 1;
}
});
You could try something like this but I didn't test it
$('td').each(function(){
var text = this.html();
$('td:contains("'+text+'"):nth-child(2)').css({'background':'orange'});
$('td:contains("'+text+'"):nth-child(3)').css({'background':'red'});
});
Edit:
Not particularly elegant but it seems to work
http://jsfiddle.net/63L7L/1/
var second = [];
var third = [];
$('td').each(function(){
var text = $(this).html();
second.push($("td").filter(function() {
return $(this).text() === text;
})[1])
third.push($("td").filter(function() {
return $(this).text() === text;
})[2])
});
$(second).each(function(){
$(this).css({'background':'red'});
});
$(third).each(function(){
$(this).css({'background':'orange'});
});
With pure Javascript (ECMA5)
CSS
.orange {
background-color:orange;
}
.red {
background-color:red;
}
Javascript
Array.prototype.forEach.call(document.querySelectorAll('.table-striped td'), function (td) {
var textContent = td.textContent;
if (this.hasOwnProperty(textContent)) {
td.classList.add(++this[textContent] === 2 ? 'orange' : 'red');
} else {
this[textContent] = 1;
}
}, {});
On jsFiddle

How do I output the contents of an array in an html table while using jQuery?

How do I display the contents of an array in a HTML table while using jQuery?
Here's my script... This outputs the objects in the array on top of the table not in the table.
HTML
<table>
<thead>
<tr>
<th>ITEM ID</th>
<th>NUMBER OF BAGS</th>
<th>WEIGHT</th>
</tr>
</thead>
<tbody>
<div id="returnlist"></div>
</tbody>
</table>
jQuery
var tempList = new Array();
$('#add').click(function(){
var split = $('#onhanditem').val().split('_');
var itemid = split['0'];
var kilo = $('#kilo').val();
var bagsReturned = $('#bagsReturned').val();
var totalbagkiloreturned = kilo+'_'+bagsReturned;
tempList[itemid] = totalbagkiloreturned;
list = '';
// i = ITEM ID | tempList = totalbagkiloreturned
for (var i in tempList){
var itemID = i;
var split = tempList[i].split('_');
var kilo = split['0'];
var numBags = split['1'];
list+='<tr><td>'+itemID+'</td><td>'+kilo+'</td><td>'+numBags+'</td></tr>';
}
$('#returnlist').html(list);
});
});
As far as I'm aware, the middle of a table isn't a valid location for a <div> tag, which is why it's not being displayed inside the table. Why not put your id on the <tbody> tag instead, and do away with the div altogether?
You can't have a div inside a table, it's simply not valid HTML.
Try the following HTML instead
<table>
<thead>
<tr>
<th>ITEM ID</th>
<th>NUMBER OF BAGS</th>
<th>WEIGHT</th>
</tr>
</thead>
<tbody id="returnlist">
</tbody>
</table>

Categories

Resources