Javascript - copy date/time in each new row - javascript

I have a form with this filed and by ADD button I can add rows: book_date[], book_desc[], book_pages[].
<form method="POST" action="addpages.php" name="books" onmouseover="javascript:sum();">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<table id="dataTable" class="form">
<input type="text" class="form-control" name="date_book[]">
<input type="text" class="form-control" name="book_pages[]">
<input type="text" class="form-control" name="book_pages_total">
</table>
</form>
When add a new row I want the value inside the first filed date_book was copyed in the new row.
I try ti use this start script, but this not work for new row.
var $date_book= $("#date_book[]");
$date_book.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $date_book[].val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$date_book[].val(v1);
v2 = v1;
}
};
How to copy the date values write in in the filed date_book[] in each new row?
I hope to explain my problem.
Thanks

You should start with valid HTML, an input can't be a child of a table. I've just mocked–up something based on the names.
After fixing that, in POJS you can just clone the last row and add it to the table. That will also clone whatever values the form controls happen to have at the time, so if you only want to keep the first value, then do that and clear the others, e.g.
function addRow(tableId) {
var table = document.querySelector('#' + tableId);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {if (i) input.value = '';});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
<form name="books">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td><input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td><input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td><input type="text" class="form-control" name="book_pages_total">
</table>
</form>

Related

Create row with unique ID in javascript

Below is my javascript function to add new row to <table> in HTML. I need a unique row id for each table row. Below is my code :
$(document).ready(function(){
var html = '<tr><td class="cb"><input class="form-control" type="text" value="" id="inputString" name="inputString"/><div id="showList"><ul class="list-group"></ul></div></td><td><input type="checkbox" name="debit" class="form-control"></td><td><input type="checkbox" name="credit" class="form-control"></td><td><input type="number" name="amount" class="form-control"></td><td><input class="btn btn-warning" type="button" name="remove" id="remove" value="Remove" onclick="removeMe(this);"></td></tr>';
var x=1;
$("#add").click(function(){
$("#table_field").append(html);
});
});
How can I achieve this in the same function
I tried creating unique ids but not able to do.. Please help me
I need a unique row id for each table row.
To add an id to each row while adding you just have to pass it on $("#table_field").append(). Below I am using the length of tr inside #table_field to set an id.
$("#add").click(() => {
const
tTable = $("#table_field"),
tID = `tr${tTable.find('tr').length}`;
tTable.append(
`<tr id = '${tID}'><td>${tID}</td></tr>`
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id = 'table_field'></table>
<button id = 'add'>Add</button>
You can adjust the logic of generating the id to how you see fit. Like using Math.random or Date ticks.

Change text in specific table cell by user input and Javascript

How can a change the content of a cell based on user input?
The user should be able to change both the cell and the text in that cell.
This is an example of the table I want to use (without td id):
<table border="1" id="tbl">
<tr><td>text</td><td>text</td><td>text</td></tr>
<tr><td>text</td><td>text</td><td>text</td></tr>
</table>
This is some input fields, I guess:
<label for="row">Row: </label>
<input type="number" id="row" value="1" />
<label for="col">Column: </label>
<input type="number" id="col" value="1" />
<label for="textOut">Tekst: </label>
<input type="text" id="tblText" name="text" value="Some text"/>
<button onclick="changeTable()">Change cell</button>
And this is where I get lost... I've searched the web for hours, and I've tried many different things, but I'm completely stuck. No need to say I'm really new to JavaScript...
var tbl = document.getElementById("tbl");
function changeTable () {
var row = document.getElementById("tbl").rows;
var col = row[0].cells;
col[0].innerHTML = document.getElementById("tblText").value;
}
You got pretty far already. Al you needed to do is get the target row and column, compensate for an array starting at 0, validate user input to be no less then 1 and no more then the size of columns and rows.
If you don't validate user input you can get errors if you enter a number below 1 or greater then the number of columns, therefore I used the Math.min and Math.max functions. Min 0 and Max size of columns/rows compensated for arrays starting at 0.
Alternatively you could pop up an alert if the user enters a value greater or smaller then allowed.
var tbl = document.getElementById("tbl");
function changeTable(){
var rowUserInput = parseInt(document.getElementById("row").value)-1; // user input compensated for arrays starting at 0
var colUserInput = parseInt(document.getElementById("col").value)-1; // user input compensated for arrays starting at 0
var row = document.getElementById("tbl").rows;
var targetRow = Math.min(Math.max(rowUserInput
, 0), // we want the maximum of user input and 0, so the value to use will never be less then 0
row.length - 1); // we want the minimum of user input and the number of rows compensated for arrays starting at 0, so we will never try to change a row higher then exists
var col = row[targetRow].cells;
var targetCol = Math.min(Math.max(colUserInput
, 0), // we want the maximum of user input and 0, so the value to use will never be less then 0
col.length - 1); // we want the minimum of user input and the number of columns compensated for arrays starting at 0, so we will never try to change a column higher then exists
if(rowUserInput !== targetRow) {
console.log('You tried to use a non existing row!');
}
if(colUserInput !== targetCol) {
console.log('You tried to use a non existing column!');
}
col[targetCol].innerHTML = document.getElementById("tblText").value;
}
<table border="1" id="tbl">
<tr><td>text row 1</td><td>text</td><td>text</td></tr>
<tr><td>text row 2</td><td>text</td><td>text</td></tr>
</table>
<label for="row">Row: </label>
<input type="number" id="row" value="1" />
<label for="col">Column: </label>
<input type="number" id="col" value="1" />
<label for="textOut">Tekst: </label>
<input type="text" id="tblText" name="text" value="Some text" />
<button onclick="changeTable()">Change cell</button>
var tbl = document.getElementById("tbl");
function changeTable () {
var row = document.getElementById("tbl").rows;
var r= document.getElementById("row").value
var c= document.getElementById("col").value
var col = row[r].cells;
col[c].innerHTML = document.getElementById("tblText").value;
}
You forgot to read the row and col number from input tag. Here I have declared two variable named r and c for row value and column value.
You simply need to get input row and col value and pass thier indexes.
var tbl = document.getElementById("tbl");
function changeTable(){
const rowId = document.getElementById("row").value;
const colId = document.getElementById("col").value;
var row = document.getElementById("tbl").rows;
var col = row[rowId - 1].cells;
col[colId - 1].innerHTML = document.getElementById("tblText").value;
}
<table border="1" id="tbl">
<tr><td>text</td><td>text</td><td>text</td></tr>
<tr><td>text</td><td>text</td><td>text</td></tr>
</table>
<label for="row">Row: </label>
<input type="number" id="row" value="1" />
<label for="col">Column: </label>
<input type="number" id="col" value="1" />
<label for="textOut">Tekst: </label>
<input type="text" id="tblText" name="text" value="Some text" />
<button onclick="changeTable()">Change cell</button>
Assuming you enter correct existing Row and Column numbers, your function changeTable should be
function changeTable(){
// Get all the rows of the table
var rows = document.getElementById("tbl").rows;
// Target row and col index
var targetRow = document.getElementById("row").value;
var targetCol = document.getElementById("col").value;
// Target row with all its cells
var targetRowCells = rows[targetRow].cells;
// Target row with the target col (target cell) changed with the new value
targetRowCells[targetCol].innerHTML = document.getElementById("tblText").value;
}

Append html string as a table row (<tr>) via javascript-jquery

I'm trying to append an HTML string to
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$('#featureContainer').append(jfield);
When the button is clicked it will crete a input field, but if I click again it creates the input in the same row.
How can I make a new row with the input in it?
The following is my HTML code
<tr>
<td id="featureContainer"></td>
</tr>
If I click the button for the second time it creates it in the same row.
I want it to create it in new row.
As we don't know wether trs are wrapped inside table or tbody, .... We have to look for the closest tr and then get its parent then append a new row to that parent.
So, you should replace this:
$('#featureContainer').append(jfield);
with:
$('#featureContainer').closest('tr').parent().append('<tr><td>' + field + '</td></tr>');
NOTE: that inside field you have a static ID which will be on all the inputs you spawn which will be wrong since IDs are unique. So you may want to assign diferent IDs for diferent inputs.
You can just add the html code into field variable, like below:
var field = "<tr><td id="featureContainer"><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td>
</tr>"
var jfield = $(field);
Assuming there is a button with id = 'add' and a table with id='data', then you can add this after above code:
$('#add').click(function(){
$('#data').append(jfield);
});
Your on the right track. But you don't need the jfield.
this appends the value of 'field' inside the td element:
$('#featureContainer').append(field);
but what you want is to append inside the table. So give your table a id (or the tbody) and do the following:
You need to embed the field inside a <tr><td> section and append that as a whole.
var field = var field = '<tr><td><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td></tr>';
then in the click event:
$('#tableid').append(field);
Thr issue with your code is that you are trying to append to an element using id selector. Since in a valid html there should be only a single element with an unique id, you will be appending the new element always to the same td#featureContainer.
I will suggest you to change the id to class. To select the td.featureContainer where you need to append the new element, you can check inside the clicked button element event handler and find the td.featureContainer
$(".feature").on("click", function() {
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$(this).parent().prev(".featureContainer").append(jfield);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row one">
</td>
</tr>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row two">
</td>
</tr>
</table>
First the id should be unique in the same document so better to use a common classes instead, then you could use append() to add new row (including tr/td), check the example below.
Hope this helps.
$('#add-row').on('click', function(){
var field = '<input type="text" name="featureName" class="form-control" placeholder="Feature Name" value="">'
$('table').append('<tr><td>'+field+'</td></tr>');
console.log($('table tr').length+' rows');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Default row</td>
</tr>
</table>
<button id='add-row'>Add row</button>

Clone a Textarea Field with its Value using Javascript

I have the code below, ready without errors. My problem is that, when you type a value in the TEXTAREA field the value does not copy itself along the clones in spite of what happens with the INPUT field. Try it your self below.
Thanks
//JAVASCRIPT PART
function insRow(row)
{
i=row.parentNode.parentNode.rowIndex;
var x=document.getElementById('myTable');
var new_row = x.rows[i].cloneNode(true);
x.rows[i].parentNode.insertBefore(new_row, x.rows[i].nextSibling);
}
<table id="myTable">
<tr>
<td><input size=10 type="text" name="myInput[]" value = ""/></td>
<td><textarea name="myTextArea[]" type="text" cols="10" rows="5" type="text" ></textarea></td>
<td><input type="button" id="addInv" value="Add" onclick="insRow(this)"/></td>
</tr>
<table>
wellll did you try adding it..
var x=document.getElementById('myTable');
var val = x.getElementsByTagName('textarea')[0].value;
var new_row = x.rows[i].cloneNode(true);
new_row.getElementsByTagName('textarea')[0].value = val;
x.rows[i].parentNode.insertBefore(new_row, x.rows[i].nextSibling);

HTML Dynamic div resize on javascript call

So i am using a javascript function to add rows based on need to a table. I am trying to figure out how to resize the div so that when a row is added the div increases in size to accomodate the new row. i also need the div next to it to resize so that the page keeps a uniform style. The function of the dynamic table allows for the user to add and delete rows from the table. Any help is appreciated.
Thank you.
<div class="leftboxes leftline1">
Full Name Of Detained Juvenile
</br>
<input id="detaineeLastName" onfocus="if (this.value=='Last') this.value = ''"
type="text" value="Last"/>
<input id="detaineeFirstName" onfocus="if (this.value=='First') this.value = ''"
type="text" value="First"/>
<input id="detaineeMiddleName" onfocus="if (this.value=='Middle') this.value = ''"
type="text" value="Middle"/>
</br>
Aliases
<table id="witnessTable" style="table-layout:fixed" border="1">
<tr>
<td style="width:0px"><input type="checkbox" name="chk" style="width:15px;margin-
left:18px"/></td>
<td><input id="aliasLast" onfocus="if (this.value=='Last') this.value = ''"
type="text" value="Last"/></td>
<td><input id="aliasFirst" onfocus="if (this.value=='First') this.value = ''"
type="text" value="First"/></td>
<td><input id="aliasMiddle" onfocus="if (this.value=='Middle') this.value = ''"
type="text" value="Middle"/></td>
</tr>
</table>
<input type="button" value="Add Row" onclick="addRow('witnessTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('witnessTable')" />
</br>
</div>
<div class="rightboxes rightline1">
Sex
</br>
Age
</br>
DOB
</div>
When you add or remove a row, try putting this:
var h = myTable.clientHeight;
var divRight = document.getElementById("right");
var divLeft = document.getElementById("left");
divRight.style.height = (h + 60) + "px";
divLeft.style.height = (h + 60) + "px";
Note I added an Id label to the DIVs so it's easyer to handle them.
Use jquery if that is an option:
var divOneHeight = $("#div1ID").height() + 10;
$("#div1ID").height(divOneHeight);
var divOneWidth = $("#div1ID").width() + 10;
$("#div1ID").width(divOneWidth);
Something like that. Else use javascript:
document.getElementById("div1ID").style.width += 10;
use this for adding the rows to the table and extending the div:-
var y = document.createElment("the tag of the element wanted to be created");
var x = document.getElementByClassname("tables class");
x.appendChild(y);
then use x.removeChild(); for deletion.
then change the event handler for the element you want to trigger the event, and then put the code in it the makes the changes on both the divs.
edit: i used the getElementByClassName to simplify the styling process so that the appended elements just go under the styling class of the table and only increase its size with stable shape.

Categories

Resources