Make content of a dynamically created cell bold when clicked using Javascript - javascript

HTML:
<table id="table">"
</table>
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3">
<button onclick="addRow()">Add Row</button>
Add Row Function:
function appendRow() {
var table = document.getElementById("table");
{
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = "<p onclick=\"bold()\">words</p>;
}
}
Currently empty bold function
function bold() {
}
When the text in a cell is clicked I want to make it bold, however I'm not quite sure how I would do this due to the lack of id values from having dynamically created the content of the cells.
How would I do this?

Try this:
//add parameter into onclick trigger function
cell1.innerHTML = "<p onclick=\"bold(this)\">words</p>";
function bold(obj){
//using the innerHTML to change content
obj.innerHTML = '<b>' + obj.innerHTML + '</b>';
// OR using CSS
obj.style.fontWeight = "bold"; //thx René Roth comments
}

cell1.innerHTML = "<p onclick=\"bold(this)\">words</p>;
Script:
function bold(obj) {
obj..style.fontWeight="bold";
}

Related

Check and Uncheck Checkbox

Why when I check the checkbox it works fine when I uncheck it nothing happen
<form method="get">
<table id="row">
<tr><th colspan="2" >Location</th></tr>
<tr><td>Country:</td><td><select id="country" name ="country" style="width:200px"></select></td></tr>
<tr><td>City:</td><td><select name ="city" id ="state"></select></td></tr>
<script language="javascript">
populateCountries("country", "state");
</script>
<tr><td></td><td><input onclick="myFunction()" type="checkbox" name="manualentry" value="manualentry" >Manual Entry</td></tr>
<script>
var table = document.getElementById("row");
function myFunction() {
if (document.getElementsByTagName('manualentry').checked = true) {
document.getElementById("row").deleteRow(2);
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(-1);
cell1.innerHTML = "City:";
cell2.innerHTML = '<input type="text" >';
} else {
document.getElementById("row").deleteRow(2);
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "City:";
cell2.innerHTML = '<select name ="city" id ="state"></select>';
}
}
</script>
<tr ><td colspan="2" align="right" > <input type="submit" value="Submit"></td></tr>
</table>
</form>
A couple things. GetElementsByTagName is the wrong function call, that method is used to get an array of elements by their actual HTML tag. Use GetElementsByName instead. Also, this call will return an array, so you need to specify which index it is (it will be index 0). Since checked is already a boolean value, you do not need to specify == true.
Replace if (document.getElementsByTagName('manualentry').checked = true)
with if (document.getElementsByName('manualentry')[0].checked)
You forgot a = in the if condition:
if (document.getElementsByTagName('manualentry').checked = true) {
try
if (document.getElementsByTagName('manualentry').checked == true) {

Edit functionality using javascript and local storage

Below is my code for dynamic generation of rows:
function addRow() {
var myName = document.getElementById("name");
var type = document.getElementById("type");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML=myName.value;
row.insertCell(1).innerHTML=type.value;
row.insertCell(2).innerHTML= '<input type="button" value = "Delete" onClick="Javascript:deleteRow(this)">';
row.insertCell(3).innerHTML= ' Edit';
}
and below is my code for popup after clicking on edit link:
<div class="popup">
<p>Please edit your details here</p>
<div>
<label for="firstname" id="attr_Name">Attribute Name</label>
<input type="text" id="firstname" value="" />
</div>
<div>
<label for="lastname" id="attr_Type">Attribute Type</label>
<select id="type1" ><option >Text</option><option >Paragraph</option><option >Dropdown</option></select>
</div>
<input type="button" id="button1" value="Save" onclick="saveEditedValues()"/>
<a class="close" href="#close"></a>
</div>
Now I am using local storage to save my edited values but I am not getting how to reflect it in the dynamically generated rows. Below is code for Local storage:
function saveEditedValues(){
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
var namevar1=localStorage.getItem("attributeName");
var namevar2=localStorage.getItem("attributeType");
}
Please provide some help
In order to update the table, the save function will need to be able to locate the correct row, which means you will have to pass it something like the row number.
When adding the row, define the onclick event handler of the Edit link to pass rowCount
row.insertCell(3).innerHTML= ' Edit';
Add a hidden input to your popup div
<input type="hidden" id="editingRow" />
and have the Edit function populate that value:
function Edit(rowNum) {
...
document.getElementById("editingRow").value = rowNum;
...
}
Then the saveEditedValues function can locate the row in the table and update the values
function saveEditedValues(){
...
var rowNum = document.getElementById("editingRow").value;
var row = document.getElementById("myTableData").rows[rowNum];
row.cells[0].innerHTML = myName;
row.cells[1].innerHTML = type;
...
}
like so: jsFiddle
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
myName and type are the correct values (strings). So
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
is wrong, you have to use the plain variables like this:
localStorage.setItem("attributeName",myName);
localStorage.setItem("attributeType",type);

Add new row to the table containing a drop down list on button click

I want to add a new row on button click to a table. New Row will have one textbox and one drop-down. Dropdown (select element)'s options to be added from session attribute.
I am able to add textbox using following function.
function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="abc";
cell1.appendChild(element1);
var cell3 = row.insertCell(1);
var element2 = document.createElement("select");
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.appendChild(option1, null);
}
I have one session attribute "types". I want to add one drop down list as other column to the row where options are to be added from types. I am setting the attribute "types" when page gets loaded.
I am using Java Servlet for server side.
Any help is appreciated.
<c:forEach items="${types}" var="type">
If u have session attribute "types" then u can do like this. Post ur remaining coding so i can update my answer.
var Type = 'option 1';
function AddRow() {
$('#tblTest').append(
'<tr><td>' +
'<input type="text" />' +
'<select><option>' + Type + '</option></select>' +
'</td></tr>');
}
<table id="tblTest">
<tr>
<td>
<input type="text" name="data1" value="TempData" />
</td>
<td>
<input type="button" value="Add" onclick="AddRow()" />
</td>
</tr>
</table>

Add/Remove rows dynamically in a table in javascript

I want to add/remove rows in a table dynamically. I have javascript function to add and remove the rows. But, I want the delete button beside every single row so that I can delete a particular row.
ANd I want to add a row only if the first row is completely filled.
function to remove row
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function to add rows:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);
}
my table:
<table id="tableId">
<tr><td>Host Name</td><td>Directory</td></tr>
<tr><td><input type="text"/></td><td><input type="text"/></td></tr>
<tr><td><input type="button" value="+" onclick="addRow(tableId)"/></td>
<td><input type="button" value="-" onclick="removeRowFromTable()"/></td></tr>
</table>
Any help is appreciated! Thanks in Advance!!!
If you put a delete button on each row, then:
<tr>
<td><input type="button" value="Delete row" onclick="deleteRow(this)">
<td><input type="text">
<td><input type="text">
</tr>
And the deleteRow function can be:
function deleteRow(el) {
// while there are parents, keep going until reach TR
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
// If el has a parentNode it must be a TR, so delete it
// Don't delte if only 3 rows left in table
if (el.parentNode && el.parentNode.rows.length > 3) {
el.parentNode.removeChild(el);
}
}
BTW, if all your rows have the same content, it will be much faster to add a row by cloning an existing row:
function addRow(tableID) {
var table = document.getElementById(tableID);
if (!table) return;
var newRow = table.rows[1].cloneNode(true);
// Now get the inputs and modify their names
var inputs = newRow.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
// Update inputs[i]
}
// Add the new row to the tBody (required for IE)
var tBody = table.tBodies[0];
tBody.insertBefore(newRow, tBody.lastChild);
}
You can avoid a lot of cross browser headaches by using jquery. Here is a sample.
http://jsfiddle.net/piyushjain7/gKJEs/
Javascript has this really useful function called deleteRow where if you know the index you are deleting from, you can simply input that number, and then it'll delete that specific row (index's starting at 0 - tbl.rows.length).
I also found a nice example that uses it in action. You can adjust it to fit your needs though (although his uses checkboxes which might be a lot cleaner than just making a button next to every single row). I don't encourage you to blatantly copy the code so if there is anything that confuses you, please let us know. Hope this helps.
EDIT: I didn't see you wanted to add rows after you found out the last row was completely filled. I'll update my answer when I figure that out. However, the basic idea of that is to check if the <td> tag has text in it (perhaps check if the text inside the tag isn't a blank or if there is a <td> tag at all and then if it isn't empty, make a new <tr> element else don't.
See http://jsfiddle.net/9gnAx/
HTML & JavaScript (body):
<table id="tableId">
<tr>
<th>Host Name</th>
<th>Directory</th>
<td><input class="add" type="button" value="+" /></td>
</tr>
<tr>
<td></td><td></td>
<td><input class="add" type="button" value="+" /></td>
</tr>
</table>
<script type="text/javascript">
(function(){
var els=getElementsByClassName("add","tableId");
for(var i=0;i<els.length;i++){
els[i].onclick=addRow;
}
els[0].onclick();
})();
</script>
CSS (head):
.add,.del{
width:25px;
}
JavaScript (head):
function getElementsByClassName(c,el){
if(typeof el=='string'){el=document.getElementById(el);}
if(!el){el=document;}
if(el.getElementsByClassName){return el.getElementsByClassName(c);}
var arr=[],
allEls=el.getElementsByTagName('*');
for(var i=0;i<allEls.length;i++){
if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
}
return arr;
}
function killMe(el){
return el.parentNode.removeChild(el);
}
function getParentByTagName(el,tag){
tag=tag.toLowerCase();
while(el.nodeName.toLowerCase()!=tag){
el=el.parentNode;
}
return el;
}
function delRow(){
killMe(getParentByTagName(this,'tr'));
}
function addRow() {
var table = getParentByTagName(this,'table')
var lastInputs=table.rows.length>2?
table.rows[table.rows.length-2].getElementsByTagName('input'):[];
for(var i=0;i<lastInputs.length-1;i++){
if(lastInputs[i].value==''){return false;}
}
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.className="del";
element3.value='-';
element3.onclick=delRow;
cell3.appendChild(element3);
}
Update:
RobG has made me realize that getParentByTagName throws an error if there isn't any parent with the nodeName passed.
If you want a more general getParentByTagName, which doesn't throw errors, you can use
function getParentByTagName(el,tag){
tag=tag.toLowerCase();
while(el&&el.nodeName.toLowerCase()!=tag){
el=el.parentNode;
}
return el||null;
}
And when you call the function you should check if the result is null.
Updated jsfiddle: http://jsfiddle.net/9gnAx/1/

Add input text into html table td when double clicked

I have an html table with rows, in one of the cells I want to be able to insert an input text inside the cell whenever it is double clicked, and when this input is onblured I want to remove it and see it's value inside the td.
This is my code:
<td dir='ltr' id='test1' class='tLine' nowrap ondblclick='addInput(this);'>sdadfew</td>
function addInput(xxx) {
var id = xxx.id;
var value = document.getElementById(id).innerHTML;
document.getElementById(id).innerHTML = "<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>";
document.getElementById("input"+id).focus();
}
function closeInput(id) {
var value = document.getElementById('input'+id).value;
document.getElementById(id).innerHTML = value;
}
The problem is when I double click the input I get the text of the input inside of it.
How can I prevent this from happening? How can I resolve this issue?
UPDATE:
Inside the input I see this text:
<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>
Sorry for misunderstanding, this is the pure javascript version
javascript code
function closeInput(elm) {
var td = elm.parentNode;
var value = elm.value;
td.removeChild(elm);
td.innerHTML = value;
}
function addInput(elm) {
if (elm.getElementsByTagName('input').length > 0) return;
var value = elm.innerHTML;
elm.innerHTML = '';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', value);
input.setAttribute('onBlur', 'closeInput(this)');
elm.appendChild(input);
input.focus();
}
html code
<table>
<tr>
<td dir="ltr" id="test1" class="tLine" nowrap ondblclick="addInput(this)">sdadfew</td>
</tr>
</table>
jquery version still at http://jsfiddle.net/ZLmgZ/
Please have a look at this link
I have added some code on your function.
function addInput(xxx) {
xxx.setAttribute("ondblclick","return false");
var id = xxx.id;
var value = document.getElementById(id).innerHTML;
document.getElementById(id).innerHTML = "<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>";
document.getElementById("input"+id).focus();
}
Let me know if its work for you.

Categories