Inserting Row Into HTML Table within a FORM using Javascript - javascript

I am trying to add a row to a table that is located in a form using javascript. The code works when is it is outside of the <form> tags, but once the code is surrounded by <form>, added rows will popup for a few milli seconds and then disappear.
The attached code was tested on Firefox and Mozilla with the same results. If I remove the <form> tags, the code works fine. Any ideal on why <form> tags is causing a reload and making the added rows to disappear?
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script>
function addTableRow() {
var len = $('#vendorstbl tr').length
var table = document.getElementById("vendorstbl");
var row = table.insertRow(len);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "<select id='test"+len+"'><option name='test"+len+"'>Apple</option><option name='test"+len+"''>Sony</option></select>";
cell1.innerHTML = "<input type='text' size='25' id='product"+len+"' name='product"+len+"'' value='Enter Data'>";
}
</script>
<html>
<body>
<h3>Adding Row To Table Test:</h3>
<form>
<table class='add' id='vendorstbl'>
<tr><th>Vendor</th><th>Product</th></tr>
</table>
<button onclick='addTableRow()'>Add Row</button>
</form>
</body>
</html>

Have you considered using an AngularJS directive to accomplish this?
A simple ng-Repeat with some formatting will accomplish this in only a few lines of code.
<table>
<tr ng-repeat="person in people" ng-class="rowClass(person)">
<td>{{ person.name }}</td>
</tr>
</table>
Example: http://jsfiddle.net/xEyJZ/
Source: https://docs.angularjs.org/api/ng/directive/ngRepeat

Related

How To Grab Data In Any Table Row (HTML/JavaScript) Using Tree Traversal Methods

I have a table that looks like this -->
<table>
<tr style="display: none";><td class="index">index_value</td></tr>
<tr><td>section header</td></tr>
<tr>
<td class="name>Steven</td>
<td class="height">6 ft.</td>
<td><button class="add">Add</button></td>
</tr>
</table
and a js script that looks like this -->
<script>
$(".add").on('click', function(){
var the_name = $(this).closest("td").siblings(".name").text();
var the_type = $(this).closest("td").siblings(".type").text();
var the_index = $(this).parent().find("td.index").text();
}
</script>
As you can probably tell, I'm trying to get the values of certain td within this table. The first two variables work just fine because they are within the same table row; however, the last variable is not capturing the data I want (inside the index class).
I'm having some trouble understanding these methods of tree traversal and how I can grab data within a table row that is not the one which contains the button that is clicked. Any advice would be appreciated, thank you.
There were a few syntax errors in your code that you need to clean up, but the issue you're having with getting the value in the index cell is that you're not going far enough up the DOM tree to run the .find() command.
$(".add").on('click', function(){
var the_name = $(this).closest("td").siblings(".name").text();
var the_type = $(this).closest("td").siblings(".type").text();
var the_index = $(this).closest("table").find("td.index").text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr style="display: none";><td class="index">index_value</td></tr>
<tr><td>section header</td></tr>
<tr>
<td class="name">Steven</td>
<td class="height">6 ft.</td>
<td><button class="add">Add</button></td>
</tr>
</table>

innerHTML and html:select tag

I'm using JavaScript to add drop down in the jsp by clicking a button but somehow its not working. Can someone please help me. I need to use html:select tag.
<script language="JavaScript" type="text/javascript">
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell1 = document.createElement('td');
cell1value='';
cell1value+='<html:select property="test1" styleId="test1"> <html:option value="code1">test 1</html:option> </html:select>';
cell1.innerHTML = cell1value;
row.appendChild(cell1);
mytbody.appendChild(row);
}
</script>
html codes:
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>test1</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="test"/>
</form>
</body>
</html>
Thanks for your help
I made a jsfiddle to check it out... I think you might just need to have this javascript in the head tag.
Use F12 developer tools and try to debug the issue when you click the button. You might find that addRow() is undefined.
I also changed the code a little bit due to the fact that I am not versed in JSP - sorry! Is that what the
"<html:select..."
string was? I changed it to straight up html.
http://jsfiddle.net/e7z1efgr/
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell1 = document.createElement('td');
var cell1value = '';
cell1value += '<select class="text1"><option value="code1">test 1</option></select>';
cell1.innerHTML = cell1value;
row.appendChild(cell1);
mytbody.appendChild(row);
}
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>test1</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="test" />
</form>
</body>
</html>
Your problem is the strange HTML you are inserting:
'<html:select property="test1" styleId="test1"> <html:option value="code1">test 1</html:option> </html:select>'
should be
'<select property="test1" styleId="test1"> <option value="code1">test 1</option> </select>'
What's the purpose? If you just need it to insert rows inside the table, it works fine already:
Look here:
http://codepen.io/anon/pen/NGNJrV
Can you elaborate the question please?

Adding a row and sorting table using JavaScript

I am running into a very small issue which has taken more than two hours.
What I want is to insert a row in an HTML table and then sort it in ascending order. I've looked at this answer and thought that I can get this simple task working, but in vein.
Here is my little form and table:
Name: <input type="text" name="name" id="name"><br>
Status: <input type="text" name="status" id="status">><br>
<button onclick="myFunction(document.getElementsByName('name')[0].value,document.getElementsByName('status')[0].value)">Click</button><br><br>
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Doe, John</td>
<td>Approved</td>
</tr>
<tr>
<td>aaa, John</td>
<td>Approved</td>
</tr>
</tbody>
</table>
My inline JavaScript function looks like this:
function myFunction(name, status) {
var table = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = name;
cell2.innerHTML = status;
// The following code should sort the table.
var tbody = $('#mytable').find('tbody');
tbody.find('tr').sort(function (a, b) {
return $('td:first', a).text().localeCompare($('td:first', b).text());
}).appendTo(tbody);
}
Please note that adding a row to the table works fine, it just adds it to the top.
There are no console errors. The code which (apparently) should sort the table does not do anything. I've the subset of my HTML here on Fiddle, and yes that works fine.
I know about jQuery tablesorter plugin but do not need to use it.
This selector:
$('#mytable')
...is incorrect. Your table's ID is myTable, and IDs are case-sensitive. Here's a working version of your code with that fix.

Why can't I make a Table row using JavaScript and a <div>?

For some reason the following piece of code does not work to insert an extra table into my html document. The text is just randomly sitting at the top of the table instead of IN the table. Any ideas why it doesn't work?
<!DOCTYPE html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
}
</script>
</head>
<body>
<table>
<tr>
<th>Price</th>
<th>Location</th>
</tr>
<div id = "houseListingTable">
</div>
</table>
<button onclick = "insertTable()">Insert Table<\button>
</body>
</html>
Why doesn't the table row add itself to my table when I click on the Insert Table button? Any help is appreciated!!
There are two problems here:
Having a <div> element directly inside a <table> is invalid HTML.
Your table variable here is just a string. Overwriting it has no effect on the DOM.
To fix it:
Remove the <div> and give the <table> an ID:
<table id="houseListingTable">
<tr>
<th>Price<\th>
<th>Location<\th>
</tr>
</table>
Use this JavaScript:
var table = document.getElementById("houseListingTable");
table.innerHTML += "<tr><td>58,500</td><td>Montreal</td></tr>";
Note how I am actually overwriting the table's .innerHTML property. This is an important distinction from what you have there.
Just a couple of comments before the answer. Please note that you are missing the html tag at the begging, and that you are using the incorrect bar "\" to close tags in table headers (it should be < /th>) and in the button tag (< /button>).
Also, the div inside the table is not correct.
The code does nothing because the function just gets the innerHTML. For your purpose, the function should get what's inside the table, add a row and then paste it back on the table
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
document.getElementById("houseListingTable").innerHTML = table;
}
</script>
</head>
<body>
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
<button onclick = "insertTable()">Insert Table</button>
</body>
</html>
Your HTML is broken. The ending tags are wrong.
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
You can use the insertRow of DOM method to add rows to table by getting the table first by Id
function insertTable() {
// Find a <table> element with id="houseListingTable":
var table = document.getElementById("houseListingTable");
// Create an empty <tr> element and add it to the table:
var row = table.insertRow(table.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Append a text node to the cell1
var price = document.createTextNode('58,500')
cell1.appendChild(price);
// Append a text node to the cell2
var location = document.createTextNode('Montreal')
cell2.appendChild(location);
}

How come buttons are not changing?

I have a Jsfiddle application here.
When you access the fiddle and you see the output then please do this:
Click on the "Open Grid" link and select one of the number buttons. You will see Letter buttons appear below after selecting a number button.
Click on the "Open Grid" button again and select a different number button, you will realize that the letter buttons has changed. This is fine.
Click on the "Add Question" button, this would add a row displaying your selection from the top control.
Now this is where the problem is. Within the row you have just added, click on the "Open Grid" link and select a different number button, you should now realize within the table row that the letter buttons do not change at all when they suppose to. That is the problem I am having.
Now it used to work when in the javascript code, the code was this:
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $options = $("<td class='option'></td>");
var $answer = $("<td class='answer'>");
But as I want the controls within the table row to be displayed above one and another, I added some <tr> tags in $options and $answer so that the code now looks like this:
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $options = $("<tr><td class='option'></td></tr>");
var $answer = $("<tr><td class='answer'></tr>");
So my question is that why is it now not changing letter buttons within a table row because I have added in <tr> tags and how can this be fixed?
Also when a table row is added, why is it displaying two columns and not just one column?
You can't have <tr> elements within a <tr>. Also your HTML gets messed up with the additional markup. When clicking the "Add Question" button, I get something like that:
<tbody>
<tr class="optionAndAnswer">
<tr>
<td class="option"></td>
<input type="text" .... />
<span class="showGrid">[Open Grid]</span>
</tr>
<tr>
<td class="answer"></td>
<tr>
<td>
<input class="answerBtns" value="A" />
<input class="answerBtns" value="B" />
<input class="answerBtns" value="C" />
</td>
</tr>
</tr>
</tr>
</tbody>
This is pretty messed up and needs to be cleaned.
I've altered your fiddle to have a nicer HTML structure and still have it look the way you want: http://jsfiddle.net/w2wJs/10/
Update the on function to the following (changing selectors) and added preventDefault:
$('table').on('click','.showGrid', function(e) {
e.preventDefault();
$(".gridBtns").removeClass("gridBtnsOn");
var value = $(this)
.siblings('input[name=gridValues[]]').val();
$("#btn" + value.replace(/\s/g, '')).addClass("gridBtnsOn");
$('.optionTypeTbl').fadeToggle('slow');
$(this).parent().append($('.optionTypeTbl'));
$('.optionTypeTbl').css({
left: $(this).position().left,
top: $(this).position().top + 20
});
e.stopPropagation();
});
http://jsfiddle.net/w2wJs/9/

Categories