I want to thank you guys for your response and assistance rendered so far, i am greatful but please i wouldn't mind if you don't get tired on me.
Thanks.
Please i need help with my dynamic table, everything seems to be working fine except for my onchange event for each dynamically added row, it only inserts into the first row, but when i select an option from the second added row, the feilds to be updated from the database remains blank.
I used alert to check, and the onchange seems to be working on all rows just that it is only the first row that changes are effected to the required fields. Bellow is my code for your review.
php script at the top of the page that populates select option data from the database
<?php
$query1 = "SELECT * FROM products";
$result1 = mysqli_query($con, $query1);
$options = "";
while($row3 = mysqli_fetch_array($result1))
{
$options = $options."<option value='$row3[1]'>$row3[2]</option>";
}
?>
My Javascript
<SCRIPT language="javascript">
//function that increases the table row
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
//function that reduces the table row
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
//function that handles the summing of each row & all last column
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox12 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox23 = mainRow.querySelectorAll('[id=descript')[0].value;
var myBox1 = mainRow.querySelectorAll('[id=uprice')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var multiplier = Number(myBox2) || 0;
var myResult1 = myBox1 * multiplier;
var mresult = myResult1.toFixed(2);
total.value = mresult;
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total2 = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
console.log(total2);
$("#sumtotal").val(total2.toFixed(2));
return total2;
}
//function that gets the amount due(balance left)
function amountDue() {
var amount = parseFloat($("#sumtotal").val());
var paidd = parseFloat($("#paid").val());
var balance = amount - paidd;
$("#due").val(balance.toFixed(2));
$("#due2").val(balance.toFixed(2));
//return total2;
}
//function that updates #uprice and #descript from the data base onchange of the select box
function get_item(elementID){
$.ajax({
method:"POST",
url:"get_price.php",
data:{item2:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
//$('#descript').val(data);
$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
$('#descript').val(data);
}else{
alert('Description not available');
}
}
});
}
</SCRIPT>
My html code
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Sub Total (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" />
</td>
<td>
<select required="required" name="item" onchange="get_item('row_0')" id="item" placeholder="Item">
<option value="0"> select an item</option>
<?php echo $options;?>
</select>
</td>
<td>
<input type="text" required="required" class="small" name="descript" id="descript" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="uprice[]" oninput="calculate('row_0')" id="uprice" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="0">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" value="0.00" readonly="readonly" style="background-color: white">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" class="butto" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/>
Already mentoined here, but still: How to submit form on change of dropdown list? . When user submits form, use php fetch from databse, with isset($_POST['name'])
I was able to fix it with making the some changes in my get_item() javascript function
function get_item(dropDown){
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:dropDown.value},
success:function(data){
alert(data);
if(data!='0'){
$($(dropDown).parents('tr')[0]).find('input#descript').val(data);
//$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
}
thanks everyone.
Related
Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());
I have a form with this filed and by ADD button I can add rows. To remove the rows I have put deleteRow function, but this work only if the checkbox is on the left of the form. The checkbox must be on the right form and when press the delteRow, not work
This is the script:
<form name="books">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<button type="button" onClick="deleteRow('dataTable')"> DEL 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">
<td width="51"><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</table>
</form>
Javascript function:
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);
}
function deleteRow(tableID) {
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) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
How to remove the rows when the checkbox is on the right form?
I hope to explain my problem.
Thanks
As pointed out elsewhere, in Roljhon's answer, the problem is the line:
var chkbox = row.cells[0].childNodes[0];
To correct this, you can either change the index from row.cells[0] to the correct index (here it would, as noted in that answer, be 6) or you can make it more flexible, and simply select the appropriate <input> element from the specified <tr> (the row) variable, using the appropriate CSS selector and Element.querySelector()]:
// here we look within the <tr> represented by the 'row' variable:
var chkbox = row
// using Element.querySelector():
.querySelector(
// to find the first (if any) <input> element, with
// its 'type' attribute equal to 'checkbox' and its
// 'name' attribute equal to the string 'chk[]'
// (the square brackets are escaped because otherwise
// they're recognised as part of the CSS selector):
'input[type=checkbox][name="chk\[\]"]'
);
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);
}
function deleteRow(tableID) {
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.querySelector('input[type=checkbox][name="chk\[\]"]');
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<form name="books">
<button type="button" onClick="addRow('dataTable')">ADD Book</button>
<button type="button" onClick="deleteRow('dataTable')">DEL 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">
<td width="51">
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
</table>
</form>
JS Fiddle demo.
References:
CSS:
CSS Attribute Selectors.
JavaScript
Element.querySelector().
Your pointing to a wrong cell cell[0], it points to tthe first cell not the 6th cell where your checkbox is.
Change it to :
var chkbox = row.cells[6].childNodes[0];
I have a html-form to read out data from a database.
By clicking a button, there is the possibility to create additional input fields.
<table>
<tr>
<td>
<input type="text" id="productinput" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput2" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput3" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
</table>
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
// Create new div
var newdiv = document.createElement('div');
newdiv.innerHTML = '<br><input type="text" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>';
document.getElementById(divName).appendChild(newdiv);
// Re instantiate Awesomplete
new Awesomplete(newdiv.querySelector('input'), { list: document.querySelector('#productinputselect') });
// Set counter
counter++;
}
}
</script>
<div id="dynamicInput">
<b></b><input type="text" id="productinput4" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>
</div>
<input type="button" value="Additional Input Field" onClick="addInput('dynamicInput');">
<select name="productselect" id="productselect" size="9" onclick="sendproductnameinput()">
<?php
include("../files/zugriff.inc.php"); // database access
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optproduct" value='. $row['Name'] . '>' . $row['Name']. '</option>';
echo '<br>';
}
mysqli_close($db);
?>
</select>
So far, this works fine!
By using the following javascript-function the selected value from the -list is displayed in the first input-field.
function sendproductnameinput() {
document.formdatabase.productinput.value = document.formdatabase. productselect.value;
}
How can I get the next selected value in the second input-field and so on? This function should work in the additionally added fields, too.
You can use this :
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
document.formdatabase[i].value = document.formdatabase.productselect.value;
}
Your Select seems to be not Multiple select, so I suppose you want to put the same selected value in each input.
And if multiple select than you can use this:
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function sendproductnameinput() {
var selected = getSelectValues(document.formdatabase.productselect);
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
if(i < selected.length) {
document.formdatabase[i].value = selected[i];
}
}
}
here is a fiddle https://jsfiddle.net/586menbv/16/
Well, it depends on where the function sendproductnameinput() is defined, but if the variable counter is visible from it's scope, I would dare to write something like this:
var timesSomethingSelected = 1;
function sendproductnameinput() {
var productinput = 'productinput';
if(timesSomethingSelected > 1) {
productinput += timesSomethingSelected;
timesSomethingSelected++;
} else if(timesSomethingSelected == counter) {
//Do something if there aren't more inputs.
}
document.formdatabase[productinput].value = document.formdatabase. productselect.value;
}
this is the form
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td><label>should be auto increment(like (name1, name2, name3 ...))</label>
<input type="text" required="required" name="DONINID[]" value=""></td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
</form>
this is the script to add more => script.js:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 20){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
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) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Now the idia is how to change the label name too as we add more input box it's should be auto increment like:
name1, name2, name3, name3 and when we add it should show us.
thanks in advance.
Add a variable that tracks the next # to use and append it to the contents and name every time you add one.
HTML
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td>
<label>Name 1:</label>
<input type="text" required="required" name="name1" />
</td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
JavaScript
var nextName = 2;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 20) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = '<label>Name ' + nextName + ':</label>' +
'<input type="text" required="required" name="name' + nextName + '" />';
nextName++;
}
} else {
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
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) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Demo: http://jsfiddle.net/BenjaminRay/4jnw0t09/
how do I check for duplicate row in a table using javascript? The following is part of my code:
<table id="t1">
<tr>
<td>Text A</td>
<td>Text B</td>
<td>Cbx A</td>
</tr>
<% int count1 = -1;
for(int i=0; i<3; i++) { %>
<tr>
<td><input type="text" id="textA<%=i%>"></td>
<td><input type="text" id="textB<%=i%>"></td>
<td><select name="cbx_A<%=i%>">
<option value="A">Option1</option>
<option value="B">Option2</option>
</select>
</td
</tr>
<%count1 =i;
}%>
<tr>
<td><input type="button" onclick="check(<%=count1%>)" value="Check"></td>
</tr>
</table>
So based on this code, I will have 3 rows of text A,textB and cbxA. With that, how do I check whether user input the same values for 2 of the rows or all three rows?
I tried using servlet but theres too much work involve. So yeah is there a way to do this using java script instead?
Thanks in advance for any possible help.
Using this code it will check for duplication in one table column
then take all rows of table that are duplicated and put their ids in array
so you will get an array of rows id
but ur table has to have an id for each row
var columnNumber = 1;
var table = document.getElementById('t1');
var rowLength = table.rows.length;
var arrReocrds = new Array();
var arrCount = 0;
var listCount = 0;
var arr = new Array();
$('#t1 td:nth-child(' + colNumber + ')').each(function () {
var recordValue = $(this).html().trim();
var flagFirstTime = true;
//loop through table to check redundant of current record value
for (var i = 1; i < rowLength; i += 1) {
{
var row = table.rows[i];
var recordId = //put here row.id or anything that you can put it in the list
var cell = row.cells[colNumber - 1];
var value = cell.innerText.trim();
if (value == recordValue) {
if (!arr.contains(value)) {
if (flagFirstTime != true) {
arrReocrds[arrCount] = recordId;
arrCount++;
}
else
flagFirstTime = false;
}
else
break;
}
}
}
//create list for items in column
//to be sure that the item that has been taken and checked never be checked again by their other redundant records
arr[listCount] = recordValue;
listCount++;
});