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) {
Related
I am having a table. In every row, I will be having 5 input fields. There is a button addrow. when you click on it,it will create a new row.
addrow function(){
var table = document.getElementById("rtable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
var cell6=row.insertCell(5);
cell1.innerHTML="<td><input type='text' class='form-control' name='r1'></td>"
cell2.innerHTML="<td><input type='date' class='form-control' name='r2'></td>"
cell3.innerHTML="<td><input type='number' class='form-control' name='r3' ></td>"
cell4.innerHTML="<td><select class='form-control' name='r4'>"+
"<option value='yes' >Yes</option><option value='no' selected>No</option></select> </td>"
cell5.innerHTML="<td><input type='date' class='form-control' name='r5'></td>"
cell6.innerHTML="<td><button type='button' class='buttongreentab' onclick='remcosdeleterow(this)'>Delete</button> </td>"
}
now i want to add a functionality to 'r4'. i.e 4th cell. if my selected option is yes, then r5 should be enabled.
if my selected option is No, then r5 should be disabled. but the problem is every row will be having a cell with name r5.
I tried many options. Nothing worked. Can someone help me?
Based on suggestions, I edited my code as:
<script>
const getSelect = document.querySelectorAll('select.form-control');
getSelect.forEach(getSingleSelect => {
getSingleSelect.addEventListener('change', () => {
console.log(getSingleSelect.value);
if (getSingleSelect.value == 'yes') {
// console.log('I will render cell5.innerHTML');
cell5.innerHTML="<td style='display:none'><input type='date' class='form-control' name='os5'></td>"
} else {
console.log('I will not render cell5.innerHTML');
}
})
});
</script>
when I change my select option to yes, still there is no use. I dont understand where i am going wrong?
I am having a table. there are 5 columns. and we can add / delete the rows based on our requirement. I want to add a feature so that when someone selects yes on 4th column, 5th column should be enabled and if 4th column is no, then 5th column should be disbaled. I dont know how to achieve this? Please help me.. :(
Here is fully working code you with JS. You need to use functions like nextElementSibling and childNodes[0] to get the correct r5 from each row on select option Yes or No
When you click on add Row button you need to wrap your querySelectorAll method in a function and just call this dynamicElements() function each time you click to a new row to your table. Since we need to check each time for dynamically added element.
To disable the r5 you can simple use disabled property of the input and set it true on NO or else enable it on YES as false
I have also added functionality of removing the specific row when you click on delete button. In that you can use closest function to get the row tr and use remove() function to remove from the DOM.
Lastly, I have not changed any class in your code at all as you wanted to keep the class name OR HTML as it is!
Live Working Demo:
const addRow = () => {
const table = document.querySelector("#rtable");
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
const cell4 = row.insertCell(3);
const cell5 = row.insertCell(4);
const cell6 = row.insertCell(5);
cell1.innerHTML = "<td><input type='text' class='form-control' name='r1'></td>"
cell2.innerHTML = "<td><input type='date' class='form-control' name='r2'></td>"
cell3.innerHTML = "<td><input type='number' class='form-control' name='r3' ></td>"
cell4.innerHTML = "<td><select class='form-control' name='r4'>" +
"<option disabled selected>Choose</option><option value='yes' >Yes</option><option value='no'>No</option></select> </td>"
cell5.innerHTML = "<td><input type='date' class='form-control' name='r5'></td>"
cell6.innerHTML = "<td><button type='button' class='btn btn-danger buttongreentab' onclick='remcosdeleterow(this)'>Delete</button> </td>"
dynamicElements() //fetch all dynamic elements
}
//Call this function on addRow so that all element are fetched / watched again
function dynamicElements() {
const getSelect = document.querySelectorAll('select.form-control');
getSelect.forEach(getSingleSelect => {
getSingleSelect.addEventListener('change', (e) => {
if (e.target.value == 'yes') {
e.target.parentElement.nextElementSibling.childNodes[0].disabled = false
} else {
e.target.parentElement.nextElementSibling.childNodes[0].disabled = true
}
})
})
}
//Remove row
function remcosdeleterow(el) {
el.closest('tr').remove() //remove row onClick
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<table id="rtable"></table>
<button class="btn btn-success" onclick="addRow()">Add Row</button>
First, you need to add an Event Listener for the select field. In this case it would be a change event. It will listen to the value, here is an example:
const getSelect = document.querySelector('.select');
getSelect.addEventListener('change', () => {
console.log(getSelect.value);
if (getSelect.value == 'yes') {
console.log('I will render cell5.innerHTML');
// cell5.innerHTML='<td><input type="date" class="form-control" name="r5"></td>'
} else {
console.log('I will not render cell5.innerHTML');
}
})
<select class="select">
<option disabled selected>Select an Option</option>
<option value="yes">yes</option>
<option value="no" active>no</option>
</select>
You will need to give the select tag a class/id name (it's safer to declare a class name than the whole element tag).
The condition I made in the snipper, you can add the cell5.innerHTML="<td><input type='date' class='form-control' name='r5'></td>" in the if the value == 'yes'
Try to implement this, and let me know if you need extra help. Of course, remove the cell5.innerHTML='<td><input type='date' class='form-control' name='r5'></td>' you had, I will be in the if condition.
Also use a more modern syntax:
const addRow = () => {
const table = document.querySelector("#rtable");
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
const cell4 = row.insertCell(3);
const cell5 = row.insertCell(4);
const cell6 = row.insertCell(5);
cell1.innerHTML = "<td><input type='text' class='form-control' name='r1'></td>"
cell2.innerHTML = "<td><input type='date' class='form-control' name='r2'></td>"
cell3.innerHTML = "<td><input type='number' class='form-control' name='r3' ></td>"
cell4.innerHTML = "<td><select class='form-control' name='r4'>" +
"<option value='yes' >Yes</option><option value='no' selected>No</option></select> </td>"
cell5.innerHTML = "<td><input type='date' class='form-control' name='r5'></td>"
cell6.innerHTML = "<td><button type='button' class='buttongreentab' onclick='remcosdeleterow(this)'>Delete</button> </td>"
}
const getSelect = document.querySelectorAll('select.form-control');
getSelect.forEach(getSingleSelect => {
getSingleSelect.addEventListener('change', () => {
console.log(getSingleSelect.value);
if (getSingleSelect.value == 'yes') {
console.log('I will render cell5.innerHTML');
// cell5.innerHTML='<td><input type="date" class="form-control" name="r5"></td>'
} else {
console.log('I will not render cell5.innerHTML');
}
})
}
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";
}
I am trying to create dynamic select boxes that contain the same data, however, only the first select box contains the data and not the others.
Can someone assist me as to how I would populate the others accordingly please.
<input type="button" value="Add" onclick="addRow('dataTable')" />
<input type="button" value="Delete" onclick="deleteRow('dataTable')" />
<?php $i= 1; ?>
<table id="dataTable">
<tr>
<td><input type="checkbox" name="chkbox[]"/></td>
<td> 1 </td>
<td><select name="fireman[]"><option value=""></option><?php require("php/fireman_list.php"); ?></select> </td>
</tr>
</table>
JS CODE
<script language="javascript">
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 = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("select");
element2.type = "text";
element2.name = "fireman[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++)
{
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e)
{
alert(e);
}
}
</script>
Err... From what I understand of your code, I am not quite sure you're using the right tool for the job.
You have PHP on the server side that is meant to generate HTML pages, so why bother to do it in JavaScript? Even with the help of JQuery, adding DOM elements dynamically is a messy, verbose and tedious business.
If you want your page to display only part of its contents, the usual way of doing it is to have all the possible contents created on the page, and mask the parts that you don't want (using CSS attributes).
I assume you don't plan to allow to create on your page an infinite number of... Mmmm... whatever these dynamic table represent?
If you can set a limit to, say, 10 instances, you can create these 10 instances with a simple PHP loop (or even by copy-pasting the HTML code for a proof of concept test), and then replace your creation/destruction process with a show/hide mechanism.
Initially, only the first instance will be shown. the "Add" button will make the next one visible, and the "Delete" button will make the last one invisible.
If you index your table instances by Id (i.e. "DataTable_0", "DataTable_1", etc.), it is really easy to switch them on and off with CSS, like so:
function hide_table (table_number)
{
document.getElementById ("DataTable_"+table_number).style.display = 'none';
}
You can make them reappear just as easily using block instead of none for display property.
What do you think?
you need to change the addRow function so that it accepts two additional parameters which are arrays consists of the values and Text for options of the created select item.
selValue will be the array of values of options in select and
selText will be the array of Text of options in select
Let the code be:
function addRow(tableID, selValue, selText)
{
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 = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("select");
element2.type = "text";
element2.name = "fireman[]";
//dynamically adding data from arrays passed
for(var i=0; i<selValue.length;i++)
{
op=document.createElement("option");
op.text= selValue[i];
op.value= selText[i];
cell3.add(op);
}
// dynamic adding end
cell3.appendChild(element2);
}
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>
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/