clear a hidden input when cloning row - javascript

Im using a function to clone html table rows, with input fields, to allow the user multiple inputs.
my html looks like this
<table id="ID_1">
<tr id="tr_id1">
<td><input type="hidden" value="databaseid"/></td>
<td>Inputfield 1</td>
<td>Inputfield 2 </td>
</tr>
</table>
<button onclick="cloneRow('ID_1', 'tr_id1')"></button>
and my javascript
function cloneRow(tablename,rowname) {
var row = document.getElementById(rowname); // find row to copy
var table = document.getElementById(tablename); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
$('.pickDate').each(function() {
$(this).datepicker({ dateFormat: 'dd.mm.yy' });
});
}
For further work on the next page, I need only the first <td><input type="hidden" value="databaseid"/></td> so by copying, it should only copy the hidden input, but without the value in side, value should look like value=""
How can this be solved? (jQuery can be used)
Fiddle http://jsfiddle.net/21sv1bug/

$(row).find('input:hidden').val('')
use above after your function call

You can empty the value of the input in the row with this jQuery code:
$(row).find('input').val('')

try this:
function cloneRow(tablename,rowname) {
var value=$(this).prev('table').find('input:hidden').val(); // store the value in a variable
$(this).prev('table').find('input:hidden').val(''); // empty the input
var row = document.getElementById(rowname); // find row to copy
var table = document.getElementById(tablename); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
$(this).prev('table').find('input:hidden').val(value); // put the value in its place again
$('.pickDate').each(function() {
$(this).datepicker({ dateFormat: 'dd.mm.yy' });
});
}
UPDATE:
A Working DEMO using jQuery:
$('button').click(function(){
var clone=$(this).prev('table').find('tr:first').clone();
clone.attr('id','newID');
clone.find('input:hidden').val('');
$(this).prev('table').append(clone);
});

Related

javascript insert new row same as first row when press enter in html table last row

I want to insert new row in html table when user press enter on keyboard. At beginning I already added first tr when create the table. In this tr, first td contain html dropdown list($select_chooseitem) that contain data from database.Second column is textbox. I want to use javascript to get first tr element set and create new row based on that. tr element set would be like:
<tr>
<td>first col</td>
<td>second col</td>
</tr>
I do not want to declare new tr element set. But, want to retrieve first tr element set from table. Is this possible?
$row_html ='<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>';
$html_complete='<!DOCTYPE html>
<html lang="en">
<head>
<script>
$(function () {
// Change the selector if needed
var $table = $(".mt-table-edit");
//addNewRow();
function addNewRow() {
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td><input/></td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13) {
addNewRow();
}
});
// add template after the last row
$table.find("tbody:last-child").append($tr);
// focus on firt input of newly added row
$tr.find("td:first input").focus();
}
});
</script>
</head>
<body>
<table class="mt-table-edit">
'.$row_html.'
</table>
</body>
</html>';
echo $html_complete;
//echo $query_tbltemplateitems;
Since first one not work, other method I tried was getting $select_chooseitem in javascript to create tr element set. I tried access php variable($select_chooseitem) in js by addNewRow('.$select_chooseitem.'); ,but not working. How is proper way to access php variable value from js?
<script>
$(function () {
var $table = $(".mt-table-edit");
var $row = $(".mt-table-edit").children("tr:first");
addNewRow('.$select_chooseitem.');
function addNewRow(var)
{
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td>var</td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13)
{
addNewRow(var);
}
});
$table.find("tbody:last-child").append($tr);
$tr.find("td:first input").focus();
}
});
</script>
I have tried declare variable in js and try to access in js in head of html. not successful too.
Example:
<?php
$select_chooseitem='<select>'.$option_list.'</select>';
?>
<script>
var select_chooseitem=<?php echo $select_chooseitem;?>;
</script>
Thanks in advance.
Kindly try the code snippet below.
$(document).on( 'keyup', '.name', function(){
if (event.which == 13 && $(this).closest("tr").is(":last-child")) {
var $tblbody = $('#mytable').find("tbody"),
$tbltrlast = $tblbody.find("tr:last"),
$trnew = $tbltrlast.clone();
$tbltrlast.after($trnew);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='mytable'>
<tbody>
<tr>
<td><input type='text' name='name' class='name' value='John Doe'></td>
</tr>
</tbody>
</table>
If you want to access the first child of tr you can use this:
$('table tr:first-child')
Since you are using jQuery this code might be useful.
This code searches for a table tag then selects the first tr tag
$('table tr:first-child')
You can also achieve this using plain css
table tr:first-child{
color: red;
}
The required markup for the row is constructed.
markup = "<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>"
The table body is selected to which the table rows to be added.
tableBody = $("table tbody")
Finally the markup is added to the table body.
tableBody.append(markup)
the solution Kaptian delivered seams like a good one, but he copys the last row of the Table. if you set newrow like that, it should do the job.
var newrow = $('#mytable tr:first-child').html();
Thank you for suggestion and answers. By using .clone().appendTo() and keyup(function(e), I'm able to add new row by enter on keyboard. Every time enter, it did add new row after last tr. But ,could not limit add row will execute only when enter in last td of last row.
$(function() {
// Change the selector if needed
var $table = $(".mt-table-edit");
//var $row = $(".mt-table-edit").children("tr:first");
addNewRow();
function addNewRow() {
var $tr = $table.find("tr:eq(0)").clone();
//$(".mt-table-edit").keyup(function(e) {
//$(".mt-table-edit tr:last td:last").keyup(function(e) {
$($table.find("tbody:last-child")).keyup(function(e) {
if (event.keyCode === 13) //test enter key press on keyboard
{
//$table.find("tbody:last-child").append($tr);
$table.find("tr:eq(0)").clone().appendTo($table.find("tbody:last-child"));
}
});
$tr.find("td:first input").focus();
}
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<html lang="en">
<body>
<table class="mt-table-edit" border="1">
<tr>
<td>first col</td>
<td><input type="text" name="order"></td>
</tr>
</table>
</body>
</html>
jsfiddle
Thanks in advance.

Adding custom attribute values of dynamically created dropdowns to another element

I have a bit of HTML here:
<tr taskId="(#=obj.task.id#)" assigId="(#=obj.assig.id#)" class="assigEditRow" >
<td><select name="resourceId" class="get-resources formElements"></select></td>
<td><span class="resources-units"></span></td>
<td><span class="resources-quantity"></span></td>
<td><input type="text" placeholder="Required Q"></td>
<td align="center"><span class="teamworkIcon delAssig" style="cursor: pointer">d</span></td>
</tr>
And a bit of JS here:
'use strict';
function addResourceFunction(){
let ResourcesJSON = (json) => {
let Resources = json;
console.log(Resources);
let contactsLength = json.length;
let arrayCounter = -1;
let resID;
let resName;
let resUnit;
let resQuantity;
let Option = $('<option />');
let assignedID = $('tr.assigEditRow:last').attr("assigId");
while(arrayCounter <= contactsLength) {
arrayCounter++;
resID = Resources[arrayCounter].ID;
resName = Resources[arrayCounter].name;
resUnit = Resources[arrayCounter].unit;
resQuantity = Resources[arrayCounter].quantity;
$('.assigEditRow').last().find('select').append($('<option>', {
value: resName.toString(),
text: resName.toString(),
resourceID: resID.toString(),
resourceUnit: resUnit.toString(),
resourceQuantity: resQuantity.toString()
}));
}
}
$.getJSON("MY JSON URL IS HERE", function(json) {
ResourcesJSON(json);
});
};
So what's actually going on here: I get my data from the URL (JSON array), trigger the addResourceFunction() on click to create a new table row and to add a new select with options passed from the array. As you see from my HTML markup, the select input is placed in td.get-resources, and all that works good. I get my date set, I populate the select field and all works good. I can add as many rows/select dropdowns as I want.
Also, every option has a few custom attributes (you can see it in my JS code above), and I want to add the values of those attributes to the second and third column of the row (in HTML those are span.resources-units and span.resources-quantity). The thing is, I have no clue how to make it work 1:1, meaning that one select dropdown "alters" only units and quantity of its own row. Below is the code for that:
let idCounter = 1;
$(document).on('change', '.get-resources', function() {
$('.assigEditRow').last().find('.resources-units').attr('id', 'units-' + idCounter);
$('.assigEditRow').last().find('.resources-quantity').attr('id', 'quantity-' + idCounter);
this.resourceUn = $( ".get-resources option:selected" ).attr( "resourceUnit" );
this.resourceQuant = $( ".get-resources option:selected" ).attr( "resourceQuantity" );
$('#units-' + idCounter).append(this.resourceUn);
$('#quantity-' + idCounter).append(this.resourceQuant);
idCounter++;
});
What happens is that if I add one select input, and change options, the thing works. When I add another one and change its options, it gets attributes of the first one. Adding more - same thing. Whatever I change, it takes the attribute value of the first item added.
Try getting the id from the element instead of from the variable, since you always update the element with the id of the counter, instead of the element with the id of the row that was clicked.
Hmm, what does the counter do exactly? The more I look at it, the less I understand. What I do know is that you're not selecting the correct elements by using the idCounter to reference the correct row.
You want to do something like
$(document).on('change', '.get-resources', function() {
//var row = this;
this.find(/* Some path to the second column */).att(/* some att to change */);
this.find(/* Some path to the third column */).att(/* some att to change */);
});
where you always use the row as the root again, instead of finding a certain id, so you only update that row.
Native:
<table>
<tr>
<td>
<select>
<option data-text="resName1" data-resourceID="resID1" data-resourceUnit="resUnit1" data-resourceQuantity="resQuantity1">1</option>
<option data-text="resName2" data-resourceID="resID2" data-resourceUnit="resUnit2" data-resourceQuantity="resQuantity2">2</option>
<option data-text="resName3" data-resourceID="resID3" data-resourceUnit="resUnit3" data-resourceQuantity="resQuantity3">3</option>
</select>
</td>
<td>
<div class="column2"></div>
</td>
<td>
<div class="column3"></div>
</td>
</tr>
</table>
<script>
document.addEventListener('change', function ( event ) {
var select = event.target,
option = select.options[select.selectedIndex],
values = {
'text' : option.getAttribute('data-text'),
'resourceID' : option.getAttribute('data-resourceID'),
'resourceUnit' : option.getAttribute('data-resourceUnit'),
'resourceQuantity' : option.getAttribute('data-resourceQuantity')
},
row = select.parentNode.parentNode,/* depending on how deep the select is nested into the tr element */
column2 = row.querySelector('.column2'),
column3 = row.querySelector('.column3');
column2.textContent = 'some string with the values you want';
column3.textContent = 'some string with the other values you want';
});
</script>
Basically you start with the select that was changed, from there you get the option node that was clicked. Then you get the attributes you need from that option. Then you go up a few nodes to the row parent and find the two columns inside that row. Then you can set the content of these two columns.

Jquery get information from dynamicly added row

I have setup a function to add rows to a table and sets values to input fields. My code to add rows is as follows:
$('#addItem').click(function() {
$('#itemData tbody:last-child').append('<tr><td align="left"><input id="ItemName[]" name="ItemName[]" type="hidden" value="'+$('#itemName').val()+'">'+$('#itemName').val()+'</td><td align="left"><input id="ItemNombre[]" name="ItemNombre[]" type="hidden" value="'+$('#itemNombre').val()+'">'+$('#itemNombre').val()+'</td><td><div id="editItem" onClick="editItem(this);">edit</div> / delete</td></tr>');
var row = $(this).parent().parent().children().index($(this).parent()) - 1;
$('#itemName').val('');
$('#itemNombre').val('');
})
I would like to be able to click on "edit" for a particular row and retrieve the values of ItemName[] and ItemNombre[]. Here is a JSFiddle example
First remove the onClick="editItem(this);" call.
Then, add a function like this :
$(document).on('click', '#editItem', function(){
// Get your datas
var $this = $(this),
ItemNombre = $this.parent().parent().find('#ItemNombre').val(),
...;
// Do your stuff
// ...
});

.onchange or .onclick and checkbox value to JS script

I have an array of checkboxes group into class='year'. I would like to call a function in JS when a checkbox is checked.
The html is,
<table class="inner" id="searchTable">
<search>Exam Type:<th>
<?php
foreach($exams as $key=>$value):
echo "<tr><td class='left'><input type='checkbox' class='year' id='$key' name='$key' value='$value'
if ($category['selected'])
{
echo ' checked';
}
> $value</td></tr>";
endforeach; ?>
</table>
This table is inside a form. but I am too worried about the form at the moment.
The JS should create a table with a row when any checkbox is checked.
function yearTable(){
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
var empty = document.createTextNode("year.value");
/*var empty = document.createTextNode("");*/
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
document.getElementByClassName('year').onchange = yearTable;
I have tried using .onchange and .clicked but neither do anything when a box is checked.
Also I need the value checked in the JS.
I tried year.value but that doesn't work. Prviously I has a select options menu with id = 'exam' and I was able to get the value using exam.value but I can't figure out how to do soemthing equivalent for these checkboxes.
Any help would be greatly appreciated.
Thanks
While an html document may contain only one element with a specific id, there can be several elements with the same class.
So, there is no such a function as document.getElementByClassName. There is a function document.getElementsByClassName, and it returns an array of elements, so could call that function and then iterate over its return value, setting the needed callbacks.
Also, the code you posted must have thrown an exception at this line:
document.getElementByClassName('year')
So if you looked at developer tools in Chrome or Firebug in Firefox, you would probably see an error.
Got it,
function yearTable(){
var year = this.value;
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
if (this.checked){
var empty = document.createTextNode(year);
}
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
var checkboxes = document.getElementsByClassName('year');
for(var index in checkboxes){
checkboxes[index].onchange = yearTable;
}
Thanks

getting values of the clicked row and assigning cell's values to corresponding inputs

I have a table with id="selector".
Each row's cell has a corresponding input to it.
<td class="cell1"><b>Cell 1</b></td>
<input type="text" name="cell1" id="cell1">
What I need to do is to capture the whole row and assign certain cells to the inputs (not all cells will be assigned to inputs). In this example it would just be cell1.
<script type="text/javascript ">
$('#selector tr').click(function() {
var values = ($(this).html()); // this is the whole row
// no idea what to do now
$("#cell1").val($(this)) // don't know how to select cell1
});
</script>
EDIT: #sub1 -> #cell1
There is no need to "capture the whole row" via html().
$('#selector tr').click(function() {
$("#sub1").val( $(this).find("td").get(0).text() );
});

Categories