I am need of help. I am trying to figure out the below:
<script>
var ct = 1;
function new_bank()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// bank to delete extended form elements
var delLink = 'delete';
div1.innerHTML =
document.getElementById("newbanktpl").innerHTML + delLink;
document.getElementById('newbank').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newbank');
parentEle.removeChild(ele);
findTotalA();
}
</script>
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]"/></td>
<td><input type="number" name="Ownership[]" /></td>
<td>**ADD DELETED LINK HERE** </td>
</tr>
</table>
what I am after is the delete function to be within the table - at the moment the delete function is after the newbanktpl, and I want in within... on the last ADD DELETED LINK HERE.
give the link in the template a class
clone the template
update the div's ID
assign the delIt function to the onclick of the link
give the link a data-delete attribute that references the ID to delete.
insert the clone after the last bank that was inserted
assign the clone as the new "last bank"
var ct = 1;
var tmpl = document.getElementById("newbanktpl");
var lastBank = tmpl;
function new_bank() {
var clone = tmpl.cloneNode(true);
clone.id = "bank_" + ct;
ct++;
var delLink = clone.querySelector(".delete_link");
delLink.setAttribute("data-delete", clone.id);
delLink.onclick = delIt;
lastBank.parentNode.insertBefore(clone, lastBank.nextSibling);
lastBank = clone;
}
// function to delete the newly added set of elements
function delIt() {
var id = this.getAttribute("data-delete");
var ele = document.getElementById(id);
if (ele === lastBank) {
lastBank = ele.previousElementSibling;
}
ele.parentNode.removeChild(ele);
// findTotalA();
}
#newbanktpl {
display: none;
}
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]" /></td>
<td><input type="number" name="Ownership[]" /></td>
<td><a class="delete_link" href="#">delete</a></td>
</tr>
</table>
</div>
<button onclick="new_bank()">New Bank</button>
Try adding an id to your td, then you can use it in JS.
In your HTML
<table>
<tr>
...
<td>delete</td>
</tr>
</table>
In your script tag
...
document.getElementById("delete").href="javascript:delIt('+ ct +')";
...
The Entire function should look like this:
var ct = 1;
function new_bank() {
ct++;
var div1 = document.createElement('div');
div1.id = ct;
document.getElementById("delete").href="javascript:delIt('+ ct +')";
document.getElementById('newbank').appendChild(div1);
}
P.S. I don't know why you are trying to save bytes from the computer by calling variables with such short names, it's a waist of your time, it won't make any difference to the computer, but it makes it harder to understand your code.
Related
Im display some data into table and for each row there is Delete button, when button clicked it should Delete item in array which is stored in localStorage by passing id and than Assign it back to LocalStorage.
HTML:
<table>
<tbody id="ResultProduct">
<tr class="RMAJS">
<td><input type="text" id="item1" name="itemName" value="Computer" /></td>
<td><a data-localstorage-id='ae90ac1a-64c4-49a7-b588-ae6b69a37d47' class="deletebtn">Delete</a></td>
</tr>
<tr class="RMAJS">
<td><input type="text" id="item2" name="itemName" value="Mobile" /></td>
<td><a data-localstorage-id='6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b' class="deletebtn">Delete</a></td>
</tr>
</tbody>
</table>
LocalStorage :
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"]
0: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
1: "6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"
JavaScript :
$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < getLocalStorage.length; i++) {
var Val = getLocalStorage[i]
//Here is my problem for example i want to delete this item
//"6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b" from array
//How can i do that ??
localStorage.setItem('users', JSON.stringify(??)); //Assign it back to LocalStorage.
}
$(targetElement).closest("tr.RMAJS").remove();
})
$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem('users'));
getLocalStorage = getLocalStorage.filter(e => e !== getID);
localStorage.setItem('users', JSON.stringify(getLocalStorage));
$(targetElement).closest("tr.RMAJS").remove();
});
I have a simple add function in my table.
I would like to post the name of each uploaded file on the table, but it seems like it's only working on the first 2 rows due to my var i = 0; is not working properly.
Here is my code:
<table id='datarows'>
<tr>
<td>Upload</td><td>Filename</td>
</tr>
<tr>
<td><input type="file" id="ProductImage" name="ProductImage0" onchange="getFileData(this);"/></td>
<td><input id="filename" name="filename0" type="text" /></td>
</tr>
</table>
ADD NEW PRODUCT<br />
<script>
var i = 0;
function addProduct() {
var str = '<tr><td><input type="file" id="ProductImage'+i+'"
name="ProductImage'+i+'" onchange="getFileData2(this);" /></td>'
str = str + '<td ><input id="filename'+i+'" name="filename'+i+'" type="text"
/></td></tr>';
$('#datterrows').append(str);
}
//----- Upload picture/file and add name table 1
function getFileData(myFile) {
var file = document.getElementById("ProductImage").value;
var msg = document.getElementById("filename");
msg.value = "test"+file;
}
//----- Upload picture/file and add name table 2
function getFileData2(myFile) {
var file = document.getElementById("ProductImage"+i).value;
var msg = document.getElementById("filename"+i);
msg.value = "test" + file;
}
</script>
I don't get any errors but all I see is the my input id keeps repeating it self to be productimage0 and not continuing for each element I add.
I hope someone can help, it's been pain in the a**
I have a table that makes automatically 2 calculations:
Calculation of numbers of days after the selection of arrived and departed date from two input date field with calendar, result is stored is field (nbjours)
Multiplication of 3 fields (nbcheveaux * days* price), result is stored ind field (total)
There is a button that when we click on it a new row is added. How can i reproduce the same automatic calculations on the news rows added after click ?
1- my add rows function
window. addRow = function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var tr = document.createElement("tr");
var tdNbC = document.createElement("td");
var tdDateArrive = document.createElement("td");
var tdDateDepart = document.createElement("td");
var tdNbJour = document.createElement("td");
var tdPrix = document.createElement("td");
var tdTotal = document.createElement("td");
var td3 = document.createElement("td");
var inputDateArrive = document.createElement("input");
var inputDateDepart = document.createElement("input");
inputDateArrive.type = "text";
inputDateDepart.type = "text";
inputDateArrive.setAttribute("class", "date");
inputDateDepart.setAttribute("class", "date1");
var inputNbrC = document.createElement("input");
var inputNbrJour = document.createElement("input");
var inputPrix = document.createElement("input");
var inputTotal = document.createElement("input");
var inputButton = document.createElement("button");
inputButton.type = "button";
inputButton.innerHTML = "+";
inputButton.onclick = function(){
addRow(this);
};
tdNbC.appendChild(inputNbrC);
tdDateArrive.appendChild(inputDateArrive);
tdDateDepart.appendChild(inputDateDepart);
tdNbJour.appendChild(inputNbrJour);
tdPrix.appendChild(inputPrix);
tdTotal.appendChild(inputTotal);
td3.appendChild(inputButton);
tr.appendChild(tdNbC);
tr.appendChild(tdDateArrive);
tr.appendChild(tdDateDepart);
tr.appendChild(tdNbJour);
tr.appendChild(tdPrix);
tr.appendChild(tdTotal);
tr.appendChild(td3);
table.appendChild(tr);
$(inputDateDepart).mask("99/99/9999");
$(inputDateArrive).mask("99/99/9999");
}
2- function that calculate numbers of days
$(document).ready(function() {
$('.date1').change(function() {
var start = $('.date').datepicker('getDate');
var end = $('.date1').datepicker('getDate');
if (start<end) {
var days = (end - start)/1000/60/60/24;
$('.days').val(days);
}
else {
alert ("Depated date must be greater that arrived date!");
$('.date').val("");
$('.date1').val("");
$('.days').val("");
}
}); //end change function
}); //end ready
3- Function that operate the multiplication
$('.nbrcevaux,.days,.price').keyup(function() {
var nbrcevaux = parseInt($('.nbrcevaux').val());
var days = parseInt($('.days').val());
var prix = parseInt($('.price').val());
$('.total').val(nbrcevaux * days * prix );
});
4- HTML Table
<table>
<tr>
<td class="centrer">Nbr de chevaux</td>
<td class="centrer">Arrived Date</td>
<td class="center">Departed Date</td>
<td class="centrer">Nb/Days</td>
<td class="centrer">Prix/jr/ cheval/boxe</td>
<td class="centrer"> Total</td>
</tr>
<tr>
<td><input type="text" name="nbrcevaux" class="nbrcevaux" /></td>
<td><input type="text" name="datearrive" class ="date"/> </td>
<td><input type="text" name="datedepart" class ="date1" /></td>
<td><input type="text" name="nbrjours" class ="days" /></td>
<td><input type="text" name="prix" class="price" /></td>
<td><input type="text" name="total" class="total" /></td>
<td><button type="button" onClick ="addRow(this)">+</button> </td>
</tr>
How can i integrate the functions calculate numbers of days and multiplication in the added new row displyed after click ?
So, I was bored and tackled your question, by rewriting it because you had quite a bit of superfluous code.
Your main issue (with the calculations on the added rows) stems from the fact that you were relying on classes to uniquely identify elements, but that won't cut it. Each new row and element within the row needs to have its own unique id.
I also took the liberty of making sure that there will only ever be one "Add row" button, as you'll see.
This working example has comments inline to help follow what's going on.
$(function() {
// Declare & initialize module wide variables to store DOM elements:
var $txtnbrcevaux = $("#nbrcevaux"), $txtDateArrive = $("#dateArrive"),
$txtDepart = $("#datedepart"), $txtnbrjours = $("#nbrjours"), $txtPrix = $("#prix"),
$txtTotal = $("#total"), $btnAdd = $("#btnAddRow"), $masterRow = $("#master1");
// Unique value that will identify new elements
var count = 1;
// Establish the date picker fields
$txtDateArrive.datepicker();
$txtDepart.datepicker();
// Wire up the button's click event:
$btnAdd.on("click", function(){
// Make a copy of the last row
var newTR = $("tr[id=master" + count + "]").clone(true);
// Update the new row's id to be unique
newTR[0].id = "master" + (count + 1);
// Loop through the child elements and modify their id's so that they are unique
newTR.children().each(function(index){
if(this.children.length > 0){
// Wipe out old (copied values)
this.firstChild.value = "";
var oldID = this.firstChild.id;
this.firstChild.id = oldID.substring(0, oldID.length) + (count + 1);
// Cloning datepickers creates problems because the clones remain bound to the
// original input element. Here, we'll create a new input element and then
// insert it where the current one is, then we'll remove the current one:
if($(this.firstChild).is(".date, .date1")){
var newPicker = document.createElement("input");
newPicker.id = this.firstChild.id;
newPicker.name = this.firstChild.name;
newPicker.setAttribute("class", this.firstChild.className.replace(" hasDatepicker", ""));
newPicker.style.width = "80px";
// Set up the new datepicker:
$(newPicker).insertAfter(this.firstChild);
$(this.firstChild).remove();
$(newPicker).datepicker();
}
}
});
// Increment the count so the next row will use the next number for its id's
count++;
// Hide the last row's button
this.style.display = "none";
// Add the new row to the table
$("table").append(newTR);
// Commented due to not having plugin available
// $(inputDateDepart).mask("99/99/9999");
// $(inputDateArrive).mask("99/99/9999");
});
$('.nbrcevaux, .days, .price').on("keyup", function() {
var nbrCevaux = this.parentElement.parentElement.querySelector(".nbrcevaux").value;
var days = this.parentElement.parentElement.querySelector(".days").value;
var prix = this.parentElement.parentElement.querySelector(".price").value;
// Your problem was that you were trying to work with values from
// classes and not specific elements. Changing the function to expect
// the data to be passed to it and having it return the answer allow
// you to control what goes in and where to put what comes out
this.parentElement.parentElement.querySelector(".total").value = nbrCevaux * days * prix;
});
$txtDepart.change(function() {
var start = $txtDateArrive.datepicker('getDate');
var end = $txtDepart.datepicker('getDate');
if (start < end) {
var days = (end - start)/1000/60/60/24;
$txtnbrjours.val(days);
} else {
alert ("Depated date must be greater that arrived date!");
$txtDateArrive.val("");
$txtDepart.val("");
$txtnbrjours.val("");
}
}); //end change function
}); //end ready
/* This is only added to shrink things down so they appear within the space allotted */
input[type=text] {width:80px;}
body {font-size:.5em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<table>
<tr>
<td class="centrer">Nbr de chevaux</td>
<td class="centrer">Arrived Date</td>
<td class="center">Departed Date</td>
<td class="centrer">Nb/Days</td>
<td class="centrer">Prix/jr/ cheval/boxe</td>
<td class="centrer"> Total</td>
</tr>
<tr id="master1">
<td><input type="text" id="nbrcevaux" name="nbrcevaux" class="nbrcevaux"></td>
<td><input type="text" id="dateArrive" name="dateArrive" class ="date"></td>
<td><input type="text" id="datedepart" name="dateDepart" class ="date1"></td>
<td><input type="text" id="nbrjours" name="nbrjours" class ="days"></td>
<td><input type="text" id="prix" name="prix" class="price"></td>
<td><input type="text" id="total" name="total" class="total"></td>
<td><button type="button" id="btnAddRow">+</button> </td>
</tr>
</table>
i need to get the second td span value based on tr id
`
<table><tr id="1">
<td style="width:150px;"><span id="1">C </span></td>
<td><span style="width:800px;">hello world</span></td>
<td><input type="checkbox" name="1" onclick="KeywordText(1);" value="1"></td>
</tr>
<tr id="2">
<td style="width:150px;"><span id="2">Dot Net </span></td>
<td><span style="width:800px;">Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai</span></td>
<td><input type="checkbox" name="2" onclick="KeywordText(2);" value="2"></td>
</tr></table>
This assumes you want the second span
JavaScript:
var row = document.getElementById("rowId");
var spans = row.getElementsByTagName("span");
var secondSpan = spans[1];
jQuery:
var secondSpan = $("#rowId span:eq(1)");
It you want the span inside the second table cell
JavaScript:
var row = document.getElementById("rowId");
var cells = row.getElementsByTagName("td");
var spans = cells.getElementsByTagName("span");
var secondSpan = spans[0];
or with querySelector
var span = document.getElementById("rowId").querySelector("td + td > span");
jQuery:
var secondSpan = $("#rowId td:eq(1) span");
And spans do not have a value, you either what its html or its text.
JavaScript:
var text = secondSpan.innerHTML;
jQuery:
var text = secondSpan.html(); // or secondSpan.text();
function KeywordText(id) {
var td = document.getElementById(id).cells[1];
console.log(td.firstChild.innerHTML); // "hello word" if id == 1
}
example: http://jsfiddle.net/n2t4Z/
Strictly speaking, you can do it like this:
getSpanValueByRowId(1);
function getSpanValueByRowId(rowID) {
var row = document.getElementById(rowID);
var cells = row.getElementsByTagName("td");
var span = cells[1].getElementsByTagName("span")[0];
return span.innerText;
}
Although you could use jQuery to get it, it would look like this:
function getSpanValueByjQuery(rowID){
return $("#"+rowID + " td:nth-child(2) span").text();
}
Using jQuery:
var getvalue=$(this).closest('tr').find('td:eq(1) span').val();
alert(getvalue);
I have a table within a form that I want to append new rows as the user enters input in the last row of the table.
$('table.form-table').on('input', function() {
var tableID = '#' + $(this).closest('table').attr('id');
if(jQuery(this).closest('tr').is(':last-child')) {
var currTR = $(this).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = jQuery(currTRhtml);
var checkBox = jQuery('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
jQuery(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
And the html code if needed (simplified/trimmed):
<table class="form-table" id="XXX" border="1" cellspacing="0" cellpadding="3">
<thead>
<tr class="main"><th nowrap colspan="3" align="left"
class="border-left border-top border-right">
<h3>XXX</h3></th>
</tr>
<tr>
<th>header</th>
</tr>
</thead>
<tbody>
<tr>
<input type="hidden" name="isnew" value="">
<td >
<input type="text"
name="new_text"
value="">
</td>
</tr>
</tbody>
</table>
The problem is that this works only once and does not continue appending new rows. It's as if the last-child filtering does not get reset...
Any thoughts?
The problem is that you need to use the event's target, rather than "this". Right now "this" refers to the current table, but you need to refer to the current input box and then use closest() to find its parent tr (and :first-child to make sure it's the last one). So your code needs to look more like this:
$('table.form-table').on('input', function(e) {
var tableID = '#' + $(this).closest('table').attr('id');
if ($(e.target).closest('tr').is(':last-child')) {
var currTR = $(e.target).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = $(currTRhtml);
var checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
Notice I'm passing the event as "e" and then referencing the current input box with $(e.target).
Here's a working JS fiddle.
I suspect the problem is that you need to delegate the input event as the appended rows do not exist on $(document).ready(). Try doing something like this to delegate the handler:
$(document).ready(function () {
$('table.form-table tbody').on('input', 'tr', function () {
var self = $(this),
tableID = '#' + self.closest('table').attr('id'),
currTR = self.closest('tr'),
currTRhtml = '<tr>' + currTR.html() + '</tr>',
nextRow = $(currTRhtml),
checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
if (currTR.is(':last-child')) {
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
});
Fiddle: http://jsfiddle.net/KW7ET/