how to add row in the table dynamically - javascript

How to modify the code to add row in the table dynamically by using javascript?
This is my existing code which is having other functionality. Need one button below the table to add row. I don't need a pop-up which will say how many rows do you want to add. Every single hit will add extra row.
Javascript
var editing = false;
function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
}
if (obj.tagName == 'INPUT' || obj.tagName == 'A') return;
while (obj.nodeName != 'TD' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
}
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('input');
var z = obj.parentNode;
z.insertBefore(y, obj);
z.removeChild(obj);
y.value = x;
y.className = 'inp-edit';
y.onblur = saveEdit;
y.focus();
editing = true;
}
function saveEdit() {
var area = this;
var y = document.createElement('TD');
var z = area.parentNode;
y.innerHTML = area.value;
z.insertBefore(y, area);
z.removeChild(area);
editing = false;
}
document.onclick = catchIt;
HTML
<table border=1 class="display">
<thead>
<tr class="portlet-section-header results-header">
<th class="sorting">Operator ID</th>
<th class="sorting">Status</th>
<th class="sorting">First Name</th>
<th class="sorting">Last Name</th>
<th class="sorting">Email</th>
<th class="sorting">Role</th>
<th class="sorting_disabled">Select All
<br />
<input type="checkbox" onclick="checkAll(this);" name="check" />
</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Test1</td>
<td>Active</td>
<td>wsrc</td>
<td>wsrc</td>
<td>aa#aa.com</td>
<td>SE Admin</td>
<td>
<input type="checkbox" value="3" onclick="checkAllRev(this);" name="deleteItem" />
</td>
</tr>
<tr class="even">
<td>Test2</td>
<td>Inactive</td>
<td>EAI</td>
<td>SUBSYSTEM</td>
<td>aa#aa.com</td>
<td>API</td>
<td>
<input type="checkbox" value="4" onclick="checkAllRev(this);" name="deleteItem" />
</td>
</tr>
<tr class="odd">
<td>Test3</td>
<td>Inactive</td>
<td>Dunning</td>
<td>Portal</td>
<td>aa#aa.com</td>
<td>API</td>
<td>
<input type="checkbox" value="5" onclick="checkAllRev(this);" name="deleteItem" />
</td>
</tr>
</tbody>
</table>

You can make a template html for your row to be added, and append that html on click of the button.
For example, the row to be added contained two columns and looked some thing like this:
<tr>
<td>Test</td>
<td>Active</td>
</tr>
You can save this template in a variable. For example:
var template = "<tr><td>Test</td><td>Active</td></tr>";
Now append function of jQuery can be used to add row dynamically.
Since you need to add the row to tbody, following code can be used:
$("tbody").append(template);
A similar approach can be used to achieve your desired task.

Related

getting error after executing the code TypeError: display is nullscript.js:22:22

HTML
This a HTML page I made to add row in the tables one by one below one another when user clicks on 'add' button and gives me error as below.
<div id="adder">
<table id="adderhd">
<tr>
<th>PARTICULARS</th>
<th>Amount</th>
</tr>
<tr>
<th><input type="text" id="particulars" value=""></th>
<th><input type="number" id="amount" value=""><button id="add">Add</button></th>
</tr>
</table>
</div>
<div id="tables">
<div>
<table class="table-1">
<tr>
<th>
PARTICULARS
</th>
<th>
AMOUNT
</th>
</tr>
</table>
</div>
</div>
JavaScript
This is a JavaScript code I wrote for it but after executing this I got error on console.
Please help me I am a beginner in JavaScript.
function rowAdder() {
var particulars = document.getElementById("particulars").value;
var amount = document.getElementById("amount").value;
if (!particulars || !amount) {
alert("Please enter the values inside all the field.");
return;
}
var display = document.getElementById("table-1");
var newRow = display.insertRow(row); //not working (insert(row));
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
cel1.innerHTML = particulars;
cel2.innerHTML = amount;
row++;
}
You need to add an event onclick on the button to call rowAdder function. Variable 'display' is getting element by id, so assign id="table-1" to your html element . Its working fine.
function rowAdder() {
var particulars = document.getElementById("particulars").value;
var amount = document.getElementById("amount").value;
if (!particulars || !amount) {
alert("Please enter the values inside all the field.");
return;
}
var display = document.getElementById("table-1");
var newRow = display.insertRow();
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
cel1.innerHTML = particulars;
cel2.innerHTML = amount;
}
<div id="adder">
<table id="adderhd">
<tr>
<th>PARTICULARS</th>
<th>Amount</th>
</tr>
<tr>
<th><input type="text" id="particulars" value=""></th>
<th><input type="number" id="amount" value="">
<button onclick="rowAdder()"id="add">Add</button></th>
</tr>
</table>
</div>
<div id="tables">
<div>
<table id="table-1">
<tr>
<th>
PARTICULARS
</th>
<th>
AMOUNT
</th>
</tr>
</table>
</div>
</div>

How to echo the variable in javascript which inside a function and store it in the php variable [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have an html table and textboxes where on click on an row the row details get inserted in the textboxes all i want is to store those same values which are getting inserted into textboxes in a php variable so i can echo it or use the variable for someother purposes. How to print the f1.value in php. I want to store the f1.value in a variable and echo it in php so i can use it for my use case. i'm able to print through document.write, but i want to store the value in a php variable. f1.value changes dynamically as i click on a html table row.
(function () {
if (window.addEventListener) {
window.addEventListener('load', run, false);
} else if (window.attachEvent) {
window.attachEvent('onload', run);
}
function run() {
var t = document.getElementById('myTable');
t.onclick = function (event) {
event = event || window.event; //IE8
var target = event.target || event.srcElement;
while (target && target.nodeName != 'TR') { // find TR
target = target.parentElement;
}
//if (!target) { return; } //tr should be always found
var cells = target.cells;
//var cells = target.getElementsByTagName('td'); //alternative
if (!cells.length || target.parentNode.nodeName == 'THEAD') {
return;
}
var f1 = document.getElementById('firstname');
var f2 = document.getElementById('lastname');
var f3 = document.getElementById('age');
var f4 = document.getElementById('total');
var f5 = document.getElementById('discount');
var f6 = document.getElementById('diff');
f1.value = cells[0].innerHTML;
f2.value = cells[1].innerHTML;
f3.value = cells[2].innerHTML;
f4.value = cells[3].innerHTML;
f5.value = cells[4].innerHTML;
f6.value = cells[5].innerHTML;
var df=f6.value;
//document.write(f1.value);
//document.write(f2.value);
//document.write(f3.value);
//document.write(f4.value);
//document.write(f5.value);
//document.write(df);
//console.log(target.nodeName, event);
};
}
})();
<table id="myTable" cellspacing="1">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
<th>total</th>
<th>discount</th>
<th>diff</th>
</tr>
</thead>
<tbody>
<tr>
<td>peter</td>
<td></td>parker
<td></td>28
<td></td>9.99
<td></td>20.3%
<td></td>+3
</tr>
<tr>
<td>john</td>
<td>hood</td>
<td>33</td>
<td>19.99</td>
<td>25.1%</td>
<td>-7</td>
</tr>
<tr>
<td>clark</td>
<td>kent</td>
<td>18</td>
<td>15.89</td>
<td>44.2%</td>
<td>-15</td>
</tr>
<tr>
<td>bruce</td>
<td>almighty</td>
<td>45</td>
<td>153.19</td>
<td>44%</td>
<td>+19</td>
</tr>
<tr>
<td>bruce</td>
<td>evans</td>
<td>56</td>
<td>153.19</td>
<td>23%</td>
<td>+9</td>
</tr>
</tbody>
</table>
Firstname is:
<input type="hidden" id="firstname" name="one" />
<br>Lastname is:
<input type="text" id="lastname" name="two"/>
<br>Age is:
<input type="text" id="age" />
<br>Total is:
<input type="text" id="total" />
<br>Discount is:
<input type="text" id="discount" />
<br>Diff is:
<input type="text" id="diff" />
</form>
You can't,
You want to store server side a client side var.
That's not possible

Get clicked column index from row click

I have a row click event. Recently had to add a checkbox to each row. How can I identify the clicked cell on row click event?
Or prevent row click when clicked on the checkbox.
Attempts: this.parentNode.cellIndex is undefined on the row click event.
function pop(row){
alert(row.cells[1].innerText);
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Do you want something like this? You can just check the type attribute of the source element of the event and validate whether to allow it or not, you can stop the event using e.stopPropagation();return;.
function pop(e, row) {
console.log(e.srcElement.type);
if(e.srcElement.type === 'checkbox'){
e.stopPropagation();
return;
}else{
console.log(row);
alert(row.cells[1].innerText);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event, this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
You should pass in the event details to your function and check the target property:
function pop(e){
// If the target is not a checkbox...
if(!e.target.matches("input[type='checkbox']")) {
alert(e.target.cellIndex);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event)">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Note: If you have nested elements inside the <td>, you might want to check e.target.closest("td") instead.
Note 2: You might need a polyfill for the matches method depending on which browsers you're supporting.
Here is an example if you don't want to attach a listener on every row :
document.getElementById("majorCities").addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var tr = e.target.parentElement.parentElement;
var city = tr.cells[1].innerHTML;
console.log(city+":checked="+checked);
}
});
<table id="majorCities" style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>London</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Paris</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>New-York</td>
</tr>
</table>
window.pop = function(row){
console.log('here');
var parent = row.parentNode;
Array.from(row.parentNode.querySelectorAll('tr')).forEach(function(tr, index){
if (tr === row) {
alert(index)
}
})
}
https://jsfiddle.net/sz42oyvm/
Here is for the pleasure, another example with an object containing the cities' names and a method to draw the table with ids corresponding to the name of the clicked city, so getting the clicked name is easier.
(function () {
var mySpace = window || {};
mySpace.cities = {};
mySpace.cities.pointer = document.getElementById("majorCities");
mySpace.cities.names = ["Select","City"];
mySpace.cities.data = [{"name":"Paris"},{"name":"New Delhi"},{"name":"Washington"},{"name":"Bangkok"},{"name":"Sydney"}];
mySpace.cities.draw = function(){
this.pointer.innerHTML="";
var html = "";
html+="<tr>"
for(var i=0;i < this.names.length;i++){
html+="<th>"+this.names[i];
html+="</th>"
}
html+="</tr>"
for(var i=0;i < this.data.length;i++){
html+="<tr>"
html+="<td><input id='"+this.data[i].name+"' type='checkbox'/></td>"
html+="<td>"+this.data[i].name+"</td>"
html+="</tr>"
}
this.pointer.innerHTML=html;
}
mySpace.cities.draw();
mySpace.cities.pointer.addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var city = e.target.id;
console.log(city+":checked="+checked);
}
});
})();
table {width:25%;background:#ccc;border:1px solid black;text-align:left;}
td,tr {background:white;}
th:first-of-type{width:20%;}
<table id="majorCities">
</table>

Is there a better way to setup the input checked attribute?

My first thought was to set the input checked = "javascript function() true/false" is this possible?
What I am trying to do is a select all checkbox for my forum mailbox system.
I am useing a table to display the inbox and placed the select all checkbox inside.
<form action="" method = "post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id = "setchecked" name="smessgage"value="deleteall" onclick="get_checked()"/>
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
I use
onclick="get_checked()
to call this javascript function which sets the other checkboxes checked attribute.
<script>
function get_checked()
{
if(document.getElementById("setchecked").checked)
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = true;
}
}
else
{
for(var i = 0; i < 100;++i)
{
var check_id = "smessage"+i;
if(document.getElementById(check_id))
document.getElementById(check_id).checked = false;
}
}
}
</script>
The php to set the table up looks like this.
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if(isset($row['to_']) && $row['to_'] == $_SESSION['user_name'])
{
$id_ = isset($row['id']) ? $row['id'] : '';
$top_ = isset($row['subject']) ? $row['subject'] : '';
$auth_ = isset($row['from_']) ? $row['from_'] : '';
$date_ = isset($row['date']) ? $row['date'] : '';
echo '<tr id = "cat_" name = "cat_1">
<td style = "margin:0 auto; text-align:center;"><input type="checkbox" id = "smessage'.$i.'" name="smessgage" value="'.$id_.'"/></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$auth_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
$top_.'</a></td>
<td style = "margin:0 auto; text-align:center;"><a href = "mail?from='.$auth_.'&mail_id='.$id_.'&mail_name='.$top_.'">'.
time_elapsed_string($date_,true).'</a></td></tr>';
++$i;
}
}
This works as expected but seems a bit overkill. I just want to know if there is a more relastic approach or something that I missed while looking over input types?
Here is your improved version. Basically you just need to use same class for all checkbox before each line of your message, so that you can use jQuery.each() function to select all and toggle the checked property based on your main checkbox, which has id "setchecked"
Hope this help,
KD Quality
function checkAll(bx) {
var cbs = jQuery(".checkbox_class").each(function() {
jQuery(this).prop('checked', jQuery('#setchecked').prop('checked'));
});
}
var e = document.getElementById('setchecked'); e.onclick = checkAll;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="post">
<table rules="all">
<tr>
<th>
<input type="checkbox" id="setchecked" name="smessgage" value="deleteall" />
</th>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_1" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_2" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
<tr>
<td>
<input type="checkbox" name="messgage[]" value="message_3" class="checkbox_class" />
</td>
<td>Message 1</td>
<td>Message 1</td>
<td>Some Date</td>
</tr>
</table>
</form>
You could do something like this
// The important code
function selectAll(e) {
var nodes = document.querySelectorAll('form input[type=checkbox]');
for(var i = 0; i < nodes.length; i++) {
nodes[i].checked = e.target.checked;
};
}
// This is only code to genereate input elements
var form = document.getElementById('foo');
for (var i = 0; i < 15; i++) {
var input = document.createElement('input');
input.type = "checkbox";
form.appendChild(input);
}
<input id="selectall" type="checkbox" onclick="selectAll(event)" />
<label for="selectall">Select all</label>
<hr />
<form id="foo"></form>

JQuery issue using closest to find text inputs

I currently am outputting two tables in each iteration of a foreach loop (c# razor view although that isn't too relevant here). I wrap these two tables in a div with class = jq-roundContainer and each input in both tables has class jq-hitOrMiss. I am trying to sum up the number of X's entered into the text inputs as follows but variable sum is 0 (when I know it shouldnt be) and inputs.length is 0 also. html and simple jquery function below
html:
<div class="jq-roundContainer">
<table class="table table-bordered">
<thead>
<tr class="active">
<th colspan="2" class="text-center">1</th>
<th colspan="2" class="text-center">2</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display:none">
#Html.Hidden("EventId", Request.Params["eventId"]);
#Html.Hidden("UserId", Request.Params["userId"]);
<input type="hidden" name="scoreCards[#i].UserProfile" value="#round.UserProfile" />
</td>
<td>
<input class="jq-hitOrMiss" onchange="SumHits();" name="scoreCards[#i].Hit1StationOneShotOne" pattern="[xXoO]" type="text" maxlength="1" size="1" value="#ScoreHitMisConverter.IsHitToTableRowValue(round.Hit1StationOneShotOne)" />
</td>
#{i++;}
</tr>
</tbody>
</table>
<table class="table table-bordered">
<thead>
<tr class="active">
<th colspan="2" class="text-center">14</th>
<th class="text-center">TOTAL</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="jq-hitOrMiss" onchange="SumHits();" name="scoreCards[#i].Hit27StationThreeShotSeven" pattern="[xXoO]" type="text" maxlength="1" size="1" value="#ScoreHitMisConverter.IsHitToTableRowValue(round.Hit27StationThreeShotSeven)" />
</td>
<td class="text-center total jq-total">#round.Score</td>
#{i++;}
</tr>
</tbody>
</table>
</div>
and jquery function:
function SumHits() {
var sum = 0;
var inputs = $(this).closest('.jq-roundContainer').find('.jq-hitOrMiss');
$.each(inputs, function (index, value) {
var value = $(value).val();
if (value == 'X' || value == 'x') {
sum++;
}
});
var totalInput = $(this).closest('.jq-roundContainer').find('.jq-total');
totalInput.text(sum);
}
Inside normal function this will points to window. So when you are using an inline handler, you have to pass the this explicitly, receive it inside the function and use it.
function SumHits(_this) {
var inputs = $(_this).closest('.jq-roun.....
And in html,
<input class="jq-hitOrMiss" onchange="SumHits(this);".....
The problem arise to the this element which refers to window not the element which triggered the event. Thus you are getting the result
As you are using jQuery bind event using it like and get rid of ulgy inline-click handler.
$('.jq-hitOrMiss').on('change', SumHits)
This works for me, remove the on change on your html it is difficult to maintain
$('div.jq-roundContainer input.jq-hitOrMiss').change(function () {
var $parent = $(this).parents('.jq-roundContainer');
var sum = 0;
var inputs = $parent.find('.jq-hitOrMiss');
inputs.each(function () {
var value = $(this).val();
if (value == 'X' || value == 'x') {
sum++;
}
});
var totalInput = $parent.find('.jq-total');
totalInput.text(sum);
});
or if you want to keep your function
$('div.jq-roundContainer input.jq-hitOrMiss').change(SumHits);
function SumHits(){
var $parent = $(this).parents('.jq-roundContainer');
var sum = 0;
var inputs = $parent.find('.jq-hitOrMiss');
inputs.each(function () {
var value = $(this).val();
if (value == 'X' || value == 'x') {
sum++;
}
});
var totalInput = $parent.find('.jq-total');
totalInput.text(sum);
}

Categories

Resources