Could you please guide me how to clone last html elements using JavaScript only. I want to clone with auto incremented id throughout all. But I am seeing is cloning. I am expecting to get in this case . Am I able to explain you?
Here is the fiddle: https://jsfiddle.net/aucv3637/3/
var i = 0;
function myFunction() {
var original = document.getElementById('repeat');
var clone = original.cloneNode(true);
clone.id = "repeat" + ++i;
clone.querySelectorAll('[id="fieldName"]')[0].id = "fieldName" + i;
clone.querySelectorAll('[id="fieldType"]')[0].id = "fieldType" + i;
clone.querySelectorAll('[name="mandatory"]')[0].name = "mandatory" + i;
clone.querySelectorAll('[id="mandatory"]')[0].id = "mandatory" + i;
clone.children[2].children[0].name = "mandatory" + i;
original.parentNode.appendChild(clone);
};
<table>
<tbody id="fieldsContent">
<tr id="repeat"> <td><input type="text" id="fieldName"></td> <td>
<select name="fieldType" id="fieldType"> <option value="Date">Date</option>
<option value="String">String</option><option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td><input type="checkbox" id="mandatory" name="mandatory"> </td> </tr>
<tr id="repeat1"> <td><input type="text" id="fieldName1"></td> <td>
<select name="fieldType" id="fieldType1"> <option value="Date">Date</option>
<option value="String">String</option>
<option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td>
<input type="checkbox" id="mandatory1" name="mandatory1"> </td> </tr>
<tr id="repeat2"> <td><input type="text" id="fieldName2"></td> <td> <select name="fieldType" id="fieldType2"> <option value="Date">Date</option><option value="String">String</option>
<option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td>
<input type="checkbox" id="mandatory2" name="mandatory2"> </td> </tr>
</tbody>
</table>
<button id="start" name="start" onclick="myFunction()">
<span>Add</span>
</button>
Multiple issues in your code, updated fiddle
i not initialized
using lastChild instead of the element itself.
Not wrapping myFunction in head.
Change to
var i = 0;
function myFunction() {
var original = document.getElementById('repeat');
var clone = original.cloneNode(true);
clone.id = "repeat" + ++i;
clone.querySelectorAll('[id="fieldName"]')[0].id = "fieldName" + i;
clone.querySelectorAll('[id="fieldType"]')[0].id = "fieldType" + i;
clone.querySelectorAll('[name="mandatory"]')[0].name = "mandatory" + i;
clone.querySelectorAll('[id="mandatory"]')[0].id = "mandatory" + i;
clone.children[2].children[0].name = "mandatory" + i;
original.parentNode.appendChild(clone);
};
Edit
You need to use starts-with id selector in querySelector and last-child
function myFunction() {
var original = document.querySelector('tr[id^="repeat"]:last-child');
var match = original.id.match(/\d+$/g);
var idCounter = !!match ? +match[0] : 0;
var clone = original.cloneNode(true);
var i = (idCounter + 1);
clone.id = "repeat" + i;
console.log(clone);
clone.querySelector('[id^="fieldName"]').id = "fieldName" + i;
clone.querySelector('[id^="fieldType"]').id = "fieldType" + i;
clone.querySelector('[name^="mandatory"]').name = "mandatory" + i;
clone.querySelector('[id^="mandatory"]').id = "mandatory" + i;
clone.children[2].children[0].name = "mandatory" + i;
original.parentNode.appendChild(clone);
};
Demo
function myFunction() {
var original = document.querySelector('tr[id^="repeat"]:last-child');
var match = original.id.match(/\d+$/g);
var idCounter = !!match ? +match[0] : 0;
console.log(idCounter);
var clone = original.cloneNode(true);
var i = (idCounter + 1);
clone.id = "repeat" + i;
console.log(clone);
clone.querySelector('[id^="fieldName"]').id = "fieldName" + i;
clone.querySelector('[id^="fieldType"]').id = "fieldType" + i;
clone.querySelector('[name^="mandatory"]').name = "mandatory" + i;
clone.querySelector('[id^="mandatory"]').id = "mandatory" + i;
clone.children[2].children[0].name = "mandatory" + i;
original.parentNode.appendChild(clone);
};
<table>
<tbody id="fieldsContent">
<tr id="repeat">
<td><input type="text" id="fieldName"></td>
<td>
<select name="fieldType" id="fieldType"> <option value="Date">Date</option>
<option value="String">String</option><option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td><input type="checkbox" id="mandatory" name="mandatory"> </td>
</tr>
<tr id="repeat1">
<td><input type="text" id="fieldName1"></td>
<td>
<select name="fieldType" id="fieldType1"> <option value="Date">Date</option>
<option value="String">String</option>
<option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td>
<input type="checkbox" id="mandatory1" name="mandatory1"> </td>
</tr>
<tr id="repeat2">
<td><input type="text" id="fieldName2"></td>
<td> <select name="fieldType" id="fieldType2"> <option value="Date">Date</option><option value="String">String</option>
<option value="Integer">Integer</option>
<option value="IA5String">IA5String</option>
</select>
</td>
<td>
<input type="checkbox" id="mandatory2" name="mandatory2"> </td>
</tr>
</tbody>
</table>
<button id="start" name="start" onclick="myFunction()">
<span>Add</span>
</button>
Related
<script>
var mainlist=document.form.seleField;
//var valuelist=document.form.seleValue
//var value=new Array();
var parent = document.getElementById("id1");
var value=[]
value[0]=""
value[1]=["Monthly|M", "Bi-Weekly|BW", "Weekly|W", "Daily|D"]
value[2]=["Monday|1", "Tuesday|2", "Wednesday|3", "Thursday|4", "Friday|5", "Saturday|6", "Sunday|7"]
value[3]=["> 100|100","> 300|300", "> 500|500", "> 700|700", "> 1000|1000", "> 1500|1500", "> 2000|2000" , "> 5000|5000"]
/* function updatevalue(selectedvaluegroup){
valuelist.options.length=0
if (selectedvaluegroup>0){
for (i=0; i<value[selectedvaluegroup].length; i++)
valuelist.options[valuelist.options.length]=new Option(value[selectedvaluegroup][i].split("|")[0],
value[selectedvaluegroup][i].split("|")[1])
}
}
*/
function updatevalue(selectedvaluegroup){
parent.innerHTML = "";
if(selectedvaluegroup ==2){
for (var i=0; i<value[selectedvaluegroup].length; i++){
var chkbox = document.createElement("input");
chkbox.type = "checkbox";
chkbox.name = "day[]";
chkbox.value = value[selectedvaluegroup][i].split("|")[1];
parent.appendChild(chkbox);
var text = document.createElement("span");
text.innerHTML = value[selectedvaluegroup][i].split("|")[0];
parent.appendChild(text);
}
}
else if(selectedvaluegroup > 0){
var select = document.createElement("select");
parent.appendChild(select);
for ( i=0; i<value[selectedvaluegroup].length; i++){
var option = document.createElement("option");
option.value = value[selectedvaluegroup][i].split("|")[1];
option.text = value[selectedvaluegroup][i].split("|")[0];
select.add(option);
}
}
}
</script>
<table border="0" width="100%">
<!-- START ADD FORM -->
<form name="form" action="<?$PHP_SELF?>" method="post" onsubmit="return chkField.exec();">
<tr bgcolor="#ffffff">
<td>
<input id="txtSupplierNo" name="txtSupplierNo" size="6" maxlength="6" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$_GET['primaryID']?>" readOnly>
</td>
<td>
<input id="txtSupplier" name="txtSupplier" type="text" size = "60" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$objSupp->Supplier?>" readOnly>
</td>
</tr>
<tr bgcolor="#3399CC">
<td class="tfvNormal" id="lblField">Criteria</td>
<td class="tfvNormal" id="lblValue" colspan="3">Parameter</td>
</tr>
<tr bgcolor="#ffffff">
<td>
<select class='selectBox' name="seleField" id="seleField" onChange="updatevalue(this.selectedIndex)" tabindex="<?=++$tabindex?>">
<option value="">select a rule</option>
<option value="OrderFrequency">Order Frequency</option>
<option value="OrderDay">Order Day</option>
<option value="MinimumOrder">Minimum Order Amount</option>
</select>
</td>
<td>
<!--<select class='selectBox' name="seleValue" id="seleValue" tabindex="<//?=++$tabindex?>"></select>-->
<div id="id1">
</div>
</td>
<td align="center" colspan="2">
<input type="image" src="../../../image/add.gif" name="buttSubmit" id="buttSubmit" value="Add" style="cursor: hand;" onClick="MM_showHideLayers('Layer1','','show')" alt="Add Records" <?=$Permission?> >
</td>
</tr>
</form>
<!-- END ADD FORM -->
i have a problem to get the data and store in database.
i have two select options which are dropdown and checkbox.
i use javascript to make the checkbox and only checkbox selection can store the data in the database.
if (($_POST['buttSubmit_x'] >= 0) && ($_POST['seleField'])){
$Field = trim($_POST['seleField']);
$Value = trim($_POST['seleValue']);
$Value = '';
foreach($_POST['day'] as $selected){
$Value .= trim($selected) . "|";
}
$SupplierNo = $_POST['txtSupplierNo'];
$Supplier = $_POST['txtSupplier'];
$CreateUser = $_SESSION['userID'];
$ModifyUser = $_SESSION['userID'];
$CreateDate = date("Y-m-j");
$CreateTime = date("H:i:s");
if($Field != 'OrderDay'){
$objchEx = SQL_QUERY("SELECT * FROM SupplierEx WHERE Field='$Field' and SupplierNo='$SupplierNo'");
if($objchEx->Value && $Value <> $objchEx->Value){
$chkPara = 1;
echo"<script>";
echo"alert('Duplicate $Field ! Kindly delete the existing Parameter.');";
echo"</script>";
}
}
<table border="0" width="100%">
<!-- START ADD FORM -->
<form name="form" action="<?$PHP_SELF?>" method="post" onsubmit="return chkField.exec();">
<tr bgcolor="#ffffff">
<td>
<input id="txtSupplierNo" name="txtSupplierNo" size="6" maxlength="6" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$_GET['primaryID']?>" readOnly>
</td>
<td>
<input id="txtSupplier" name="txtSupplier" type="text" size = "60" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$objSupp->Supplier?>" readOnly>
</td>
</tr>
<tr bgcolor="#3399CC">
<td class="tfvNormal" id="lblField">Criteria</td>
<td class="tfvNormal" id="lblValue" colspan="3">Parameter</td>
</tr>
<tr bgcolor="#ffffff">
<td>
<select class='selectBox' name="seleField" id="seleField" onChange="updatevalue(this.selectedIndex)" tabindex="<?=++$tabindex?>">
<option value="">select a rule</option>
<option value="OrderFrequency">Order Frequency</option>
<option value="OrderDay">Order Day</option>
<option value="MinimumOrder">Minimum Order Amount</option>
</select>
</td>
<td>
<!--<select class='selectBox' name="seleValue" id="seleValue" tabindex="<//?=++$tabindex?>"></select>-->
<div id="id1">
</div>
</td>
<td align="center" colspan="2">
<input type="image" src="../../../image/add.gif" name="buttSubmit" id="buttSubmit" value="Add" style="cursor: hand;" onClick="MM_showHideLayers('Layer1','','show')" alt="Add Records" <?=$Permission?> >
</td>
</tr>
</form>
<!-- END ADD FORM -->
<script>
var mainlist=document.form.seleField;
//var valuelist=document.form.seleValue
//var value=new Array();
var parent = document.getElementById("id1");
var value=[]
value[0]=""
value[1]=["Monthly|M", "Bi-Weekly|BW", "Weekly|W", "Daily|D"]
value[2]=["Monday|1", "Tuesday|2", "Wednesday|3", "Thursday|4", "Friday|5", "Saturday|6", "Sunday|7"]
value[3]=["> 100|100","> 300|300", "> 500|500", "> 700|700", "> 1000|1000", "> 1500|1500", "> 2000|2000" , "> 5000|5000"]
function updatevalue(selectedvaluegroup){
parent.innerHTML = "";
if(selectedvaluegroup ==2){
for (var i=0; i<value[selectedvaluegroup].length; i++){
var chkbox = document.createElement("input");
chkbox.type = "checkbox";
chkbox.name = "day[]";
chkbox.value = value[selectedvaluegroup][i].split("|")[1];
parent.appendChild(chkbox);
var text = document.createElement("span");
text.innerHTML = value[selectedvaluegroup][i].split("|")[0];
parent.appendChild(text);
}
}
else if(selectedvaluegroup > 0){
var select = document.createElement("select");
parent.appendChild(select);
for ( i=0; i<value[selectedvaluegroup].length; i++){
var option = document.createElement("option");
option.value = value[selectedvaluegroup][i].split("|")[1];
option.text = value[selectedvaluegroup][i].split("|")[0];
select.add(option);
}
}
}
</script>
Please check the below example .Hope it helps
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var valueBtn = document.getElementById('valueBtn');
foo.addEventListener('change', function () {
bar.value = this.options[this.selectedIndex].value;
}, true);
valueBtn.addEventListener('click', function () {
console.log(bar.value)
}, true);
<select id="foo">
<option>select option</option>
<option>a</option>
<option>b</option>
</select>
<input style="display:none " type="text" id="bar">
<input type="button" id="valueBtn" value="Click and check console">
I am trying to collect data from a table that is dynamically generated on a button click. As you will see below, the button creates a new text box and a multiselect drop down. Currently, my code will only grab the first value from both the textbox and the dropdown.
My end goal is to create an object of key/values that will look like this:
{"group 1":[multiselect value, multiselect value], "group 2": [multiselect value, multiselect value, multiselect value], "group 3": [multiselect value, multiselect value]}
Below is my current code. Any guidance is appreciated!
function servicePackageAdd()
{
var serviceName = document.getElementById('servicePackageText').value;
var serviceList = document.querySelectorAll('.service');
var serviceGroupName = [];
for (var i = 0; i < serviceList.length; i++)
{
serviceGroupName.push(serviceList[i].querySelector('input.packageGroupName').value);
var sourceType = document.querySelector('select#multiple-checkboxes');
var serviceArray = [];
for (i = 0; i < sourceType.selectedOptions.length; i++)
{
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
var groupName = {};
groupName[serviceGroupName] = serviceArray;
ungroupedServiceArray = [];
}
}
document.getElementById('addGroup').onclick = duplicate;
function duplicate()
{
var original = document.getElementById('addService');
var rows = original.parentNode.rows;
var i = rows.length - 1;
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
}
var divs = ["addService"];
var visibleDivId = null;
function toggleCheckbox(divId)
{
if(visibleDivId === divId)
{
visibleDivId = null;
} else
{
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs()
{
var i, divId, div;
for(i = 0; i < divs.length; i++)
{
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId)
{
div.style.display = "block";
}
else
{
div.style.display = "none";
}
}
}
function servicePackageName()
{
var servicePackageName = document.getElementById('servicePackageText').value;
var servicePackageNameBold = servicePackageName.bold().fontcolor('#337ab7');
document.getElementById('servicePackageInputName').innerHTML = servicePackageNameBold;
}
<div>
<div class="servicePackageCreation">
<h2><b>Service Package Administration</b></h2>
<br>
<span><p><b>Create Service Package: </b></p><p id="servicePackageInputName"></p></span>
<div class="form-group">
<input type="text" class="form-inline" id="servicePackageText" minlength= 1 placeholder=" Service Package Name" required>
<button type="button" class="btn btn-primary" onclick="toggleCheckbox('addService'); servicePackageName();" id="addGroupsAndServices">Next</button>
</div>
<table>
<tr id="addService" class="service" style="display:none">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName"/>
</td>
<td>
<span><b>Add Services</b></span>
<select id="multiple-checkboxes" multiple="multiple">
<?php echo $servicehtml ?>
</select>
</td>
</tr>
<tr>
<td>
<button id="addGroup" class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>
<button type="button" class="btn btn-success test1234" onclick="confirmAddButton()" id="adminBulkConfirm">Create</button>
<br>
<br>
</div>
Using Object.values Array#map and Array#reduce.
const services = document.querySelectorAll(".service");
const res = Object.values(services)
.map((service, i) => {
const inputText = service.querySelector('.packageGroupName').value;
return {
[inputText]: [...service.querySelectorAll('option:checked')].map(o => Number(o.value))
}
})
.reduce((a, c) => ({ ...a,...c}), {});
console.log(res);
table {
display: none;
}
<table>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Banana" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple="multiple">
<option value="1" selected>12</option>
</select>
</td>
</tr>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Orange" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
<button class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>
I want to get the field-index of same-names-field i.e. 'item_id[]'.
As I select/change an item from 'Item Name' drop-down, its combo-field-index should be shown in 'span' under 'Available' against this dropdown.
Actually the purpose of getting the index of current combo is to show Available-Quantity in 'Span' against this combo under 'Available'.
(dropdown field is named 'item_id[]', index is started from 0, counting from upper most drop down to the current one)
Please copy/paste all code along with Javascript, use 'Add Rows' link and force Javascript/jQuery to work for all rows (previous and newly added elements). Thanks.
EDITED:
In short, I need to alert() the current index of item-name-combo-field after using 'Add Row' link (onchange event). This is enough for my solution (and I will manage everything else).
CODE I HAVE USED:
But it works just if used for text-box not for combo AND only for elements which are loaded on page-load not for added (appended) elements using 'Add Row' link.
var my_field = $('select[name="item_id[]"]');
my_field.on('change', function() {
var index = my_field.index( this );
alert( this.value + ', ' + index );
});
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="">
<table width="41%" border="0" align="center" cellpadding="0" cellspacing="0" id="contentstable">
<tr>
<th width="35%" align="center">Item Name </th>
<th width="14%" align="center">Quantity </th>
<th width="26%" align="center">item Sr. # </th>
<th width="18%" align="center">Store Status </th>
<th width="18%" align="center">Mode </th>
<th width="7%" align="center">Available </th>
</tr>
<tr>
<td>
<select name="item_id[]" id="item_id[]" class="combo" style="width:326px;" onchange="showIssuableQty(this.value);">
<option value="0"> </option>
<option value="1">item-1 ( Model# BN004 ) </option>
<option value="2">item-2-check ( Model# FG-56 ) </option>
<option value="3">Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD ) </option>
</select>
</td>
<td>
<input name="quantity[]" type="number" id="quantity[]" value="" class="field_3" style="width:99px;">
</td>
<td>
<input name="item_sr_no[]" type="text" id="item_sr_no[]" value="" class="field_3" style="width:199px;">
</td>
<td>
<select name="store_status[]" class="combo" id="store_status[]" style="width:119px;">
<option value="New" selected="">New </option>
<option value="Repaired">Repaired </option>
<option value="Used">Used </option>
</select>
<td>
<select name="type[]" class="combo" id="type[]" style="width:119px;">
<option value="Consume" selected="">Consume </option>
<option value="Borrow">Borrow </option>
</select>
</td>
<td>
<span id="qty_avail">Qty-Here </span>
</td>
</tr>
<tr>
<td colspan="6">
<table width="100%">
<tr>
<td width="25%" style="text-align:left; vertical-align:top; font-size:17px">
<br>
<span "> <input name="add_rows " id="add_rows " type="number " value="1 " style="width:63px; " onkeypress="handle_addRows(event); "> Add Rows </span"> </td>
<td width="55%">
<p id="issuable_qty">Issuable Qty </p>
</td>
<td width="20%" class="submittd" style="text-align:right"> <br> <input name="save" type="submit" class="submit" id="addnewcategory" value="Save Record"> </td>
</tr>
</table>
</td>
</tr>
</tbody> </table>
</form>
Javascript Used:
<script>
/*var textboxes = $('select[name="item_id[]"]');
textboxes.on('change', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
alert('abc');*/
function addMoreRow() {
var tbl_name = document.getElementById("contentstable");
var rowCount = tbl_name.rows.length;
var row = tbl_name.insertRow(rowCount - 1);
var cell1 = row.insertCell(0);
cell1.innerHTML = " <select name=\"item_id[]\" class=\"combo\" id=\"item_id[]\" onchange=\"showIssuableQty(this.value);\" value=\"\" style=\"width:326px;\" > <option> </option> <option value='1'>item-1 ( Model# BN004 ) </option> <option value='2'>item-2-check ( Model# FG-56 ) </option> <option value='3'>Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD ) </option> </select>";
var cell2 = row.insertCell(1);
cell2.innerHTML = " <input name=\"quantity[]\" type=\"number\" class=\"input\" id=\"quantity[]\" value=\"\" style=\"width:99px;\" /> <input name=\"prev_quantity[]\" type=\"hidden\" class=\"input\" id=\"prev_quantity[]\" value=\"\" style=\"width:99px;\" />";
var cell3 = row.insertCell(2);
cell3.innerHTML = " <input name=\"item_sr_no[]\" type=\"text\" class=\"input\" id=\"item_sr_no[]\" value=\"\" style=\"width:199px;\" />";
var cell4 = row.insertCell(3);
cell4.innerHTML = " <select name=\"store_status[]\" class=\"combo\" id=\"store_status[]\" value=\"\" style=\"width:119px;\" > <option value='New' selected >New </option> <option value='Repaired'>Repaired </option> <option value='Used'>Used </option> </select> <input name=\"prev_store_status[]\" type=\"hidden\" class=\"input\" id=\"prev_store_status[]\" value=\"\" style=\"width:119px;\" />";
var cell5 = row.insertCell(4);
cell5.innerHTML = " <select name=\"type[]\" class=\"combo\" id=\"type[]\" value=\"\" style=\"width:119px;\" > <option value='Consume' selected >Consume </option> <option value='Borrow'>Borrow </option> </select>";
var cell6 = row.insertCell(5);
cell6.innerHTML = " <span class=\"qty_avail\"> </span>";
}
function addRows() {
var add_rows = document.getElementById('add_rows');
//alert(add_rows.value);
for ($i = 1; $i <= add_rows.value; $i++) {
addMoreRow();
}
}
function handle_addRows(e) {
if (e.keyCode === 13) {
e.preventDefault(); // Ensure it is only this code that runs
addRows();
}
}
var itemIds = new Array('1', '2', '3');
var itemNames = new Array('', '', '');
var newItems = new Array('2357', '452', '215');
var usedItems = new Array('12', '333', '57');
var toRepairItems = new Array('234', '65', '321');
var repairedItems = new Array('789', '3', '56');
var itemThreshold = new Array('34', '56', '67');
function showIssuableQty(item_id) { // This function is not working properly, see it later.
document.getElementById('issuable_qty').innerHTML = 'abc';
var item_index = itemIds.indexOf(item_id);
var strQtyMsg = 'Issuable Qty ( <b>' + (parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) + parseInt(usedItems[item_index])) +
' </b> )' + ' <br />' + 'New ( <b>' + newItems[item_index] + ' </b> ), Repaired ( <b>' + repairedItems[item_index] + ' </b> ), Used ( <b>' + usedItems[item_index] + ' </b> )';
if (parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < parseInt(itemThreshold[item_index])) {
//if( parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < 100 ){
strQtyMsg = strQtyMsg + ' <br />Qty. below threshold ( ' + itemThreshold[item_index] + ' ) ';
strQtyMsg = strQtyMsg + ' Request Items ';
alert('Qty. is below threshold! Please generate a request to purchase.');
}
document.getElementById('issuable_qty').innerHTML = strQtyMsg;
//alert(item_index);
}
</script>
your code could be much shorter.
you should only have one item per id, so I have changed the id names
in your html to classes.
for the select in your first bit of code you can move the selector
to become an argument of the function, this means the new change
selectors will be recognised after the dom has been updated.
your first table row making function has been removed and replaced
by simply copying the html into a variable and using that to
duplicate new rows.
your last function contents have been changed to numbers to
eliminate all of the string parsing and simplify
here's a working fiddle.
$('body').on('change', 'select.combo', function() {
var $this = $(this);
var index = $this.parent().parent('tr').index();
alert($this.val() + ', ' + index);
});
var rowTemplate = $('#contentstable tr').eq(1).html(); // make a copy of the standard row html content as defined in the html
rowTemplate = '<tr>' + rowTemplate + '</tr>';
function addRows() {
var add_rows = parseFloat($('input#add_rows').val());
for (var i, i = 1; i <= add_rows; i++) {
$('#panel').before(rowTemplate); // insert the standard row above the addrow area
}
}
function handle_addRows(e) {
if (e.keyCode === 13) {
e.preventDefault(); // Ensure it is only this code that runs
addRows();
}
}
var itemIds = [1, 2, 3];
var itemNames = ['', 0, 0, 0];
var newItems = ['', 2357, 452, 215];
var usedItems = ['', 12, 333, 57];
var toRepairItems = ['', 234, 65, 321];
var repairedItems = ['', 789, 3, 56];
var itemThreshold = ['', 34, 56, 67];
function showIssuableQty(item_id) { // This function is not working properly, see it later.
// $('#issuable_qty').html('abc');
var item_index = parseFloat(item_id); // parseInt(itemIds.indexOf(item_id));
var newAndRepaired = newItems[item_index] + repairedItems[item_index];
var strQtyMsg = 'Issuable Qty ( <b>' + (newAndRepaired + usedItems[item_index]) +
' </b> )' + ' <br />' + 'New ( <b>' + newItems[item_index] + ' </b> ), Repaired ( <b>' + repairedItems[item_index] + ' </b> ), Used ( <b>' + usedItems[item_index] + ' </b> )';
if (newAndRepaired < itemThreshold[item_index]) {
//if( parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < 100 ){
strQtyMsg = strQtyMsg + ' <br />Qty. below threshold ( ' + itemThreshold[item_index] + ' ) ';
strQtyMsg = strQtyMsg + ' Request Items ';
alert('Qty. is below threshold! Please generate a request to purchase.');
}
if (item_index === 0) {
strQtyMsg = 'Issuable Qty ( </b> )';
}
$('#issuable_qty').html(strQtyMsg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="">
<table width="41%" border="0" align="center" cellpadding="0" cellspacing="0" id="contentstable">
<tr>
<th width="35%" align="center">Item Name</th>
<th width="14%" align="center">Quantity</th>
<th width="26%" align="center">item Sr. #</th>
<th width="18%" align="center">Store Status</th>
<th width="18%" align="center">Mode</th>
<th width="7%" align="center">Available</th>
</tr>
<tr>
<td>
<select name="item_id[]" id="" class="item_id[] combo" style="width:326px;" onchange="showIssuableQty(this.value);">
<option value="0"></option>
<option value="1">item-1 ( Model# BN004 )</option>
<option value="2">item-2-check ( Model# FG-56 )</option>
<option value="3">Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD )</option>
</select>
</td>
<td>
<input name="quantity[]" type="number" id="" value="" class="quantity[] field_3" style="width:99px;">
</td>
<td>
<input name="item_sr_no[]" type="text" id="" value="" class="item_sr_no[] field_3" style="width:199px;">
</td>
<td>
<select name="store_status[]" class="combo store_status[]" id="" style="width:119px;">
<option value="New" selected="">New</option>
<option value="Repaired">Repaired</option>
<option value="Used">Used</option>
</select>
<td>
<select name="type[]" class="type[] combo" id="" style="width:119px;">
<option value="Consume" selected="">Consume</option>
<option value="Borrow">Borrow</option>
</select>
</td>
<td>
<span class="qty_avail">Qty-Here </span>
</td>
</tr>
<tr id='panel'>
<td colspan="6">
<table width="100%">
<tr>
<td width="25%" style="text-align:left; vertical-align:top; font-size:17px">
<br>
<span> <input name="add_rows" id="add_rows" type="number" value="1" style="width:63px; " onkeypress="handle_addRows(event); "> Add Rows </span>
</td>
<td width="55%">
<p id="issuable_qty">Issuable Qty</p>
</td>
<td width="20%" class="submittd" style="text-align:right">
<br>
<input name="save" type="submit" class="submit" id="addnewcategory" value="Save Record">
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</form>
My problem before How do I change the select id's name after add table rows? The case is done, but one more problem is change the select id's name or number after remove rows? I have tried using replace and childnodes, but they are still not working.
For example:
I add three rows,
facility1
facility2
facility3
Then remove row for #2, this is exactly what I want
facility1
facility2
but I got,
facility1
facility3
This is the table:
<table id="tableInformation">
<tr>
<td><label>No</label></td>
<td><label>Facility</label></td>
<td><label>Currency</label></td>
<td></td>
</tr>
<tbody>
<tr>
<td><label>1</label></td>
<td><div id="facility">
<select id="facility1" name="facility">
<option value=""></option>
<option value="AL">AL</option>
<option value="BL">BL</option>
<option value="CL">CL</option>
</select>
</td>
<td><div id="currency">
<select id="currency1" name="currency">
<option value=""></option>
<option value="idr">IDR</option>
<option value="usd">USD</option>
<option value="aud">AUD</option>
<option value="jpy">JPY</option>
</select>
</td>
<td><input type="button" id="btnAddRows" value=" + "
onclick=\'addRows()\' />
<input type="button" id="btnRemRows" value=" - "
onclick=\'removeRows(this)\' />
</tr>
</tbody>
</table>
The javascript:
function addRows() {
var table = document.getElementById('tableInformation');
var rowCount = table.rows.length;
var iteration = rowCount -1;
var numbers = iteration +1;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
// Cell for number
var cell = row.insertCell(0);
var label = document.createElement('label');
label.textContent = numbers;
cell.appendChild(label);
for(var i=1; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML =
table.rows[1].cells[i].innerHTML.replace(/id="(.+)1"/,'id="$1' +
rowCount + '"');
}
}
function removeRows(index) {
var i = index.parentNode.parentNode.rowIndex;
var table = document.getElementById('tableInformation');
var rowCount = table.rows.length;
var iteration = rowCount -1;
/*var numbers = iteration +1;*/
if(iteration == 1) {
alert("Cannot remove");
}else{
table.deleteRow(i);
//alert(iteration);
for(var j=1; j<iteration; j++) {
table.rows[j].cells[0].childNodes[0].id = 'number'+(j-1+1);
table.rows[j].cells[0].childNodes[0].textContent = (j-1+1);
table.rows[j].cells[1].innerHTML.replace(/id="(.+)1"
/,'id="$1' + rowCount + '"');
table.rows[j].cells[2].innerHTML.replace(/id="(.+)1"
/,'id="$1' + rowCount + '"');
table.rows[j].cells[3].innerHTML.replace(/id="(.+)1"
/,'id="$1' + rowCount + '"');
table.rows[j].cells[4].innerHTML.replace(/id="(.+)1"
/,'id="$1' + rowCount + '"');
}
}
}
Use .cloneNode to make copy of the existing element.
Use .remove() to remove the element from the DOM.
Use querySelector to select the element from DOM by specifying selector
On remove() of every element, re-assign id attributes in a loop using setAttribute
var table = document.getElementById('tableInformation');
function addRows() {
var toClone = document.getElementById('toClone').cloneNode(true);
toClone.removeAttribute('id');
var len = table.querySelectorAll('tr').length;
toClone.querySelector('label').textContent = len;
toClone.querySelector('[name="facility"]').setAttribute('id', 'facility' + len);
toClone.querySelector('[name="currency"]').setAttribute('id', 'currency' + len);
table.appendChild(toClone.cloneNode(true));
}
function removeRows(elem) {
var trElems = table.querySelectorAll('tr');
if (trElems.length > 2) {
elem.parentNode.parentNode.remove();
trElems = table.querySelectorAll('tr');
for (var i = 1, len = trElems.length; i < len; i++) {
trElems[i].querySelector('label').textContent = i;
trElems[i].querySelector('[name="facility"]').setAttribute('id', 'facility' + i);
trElems[i].querySelector('[name="currency"]').setAttribute('id', 'currency' + i);
}
} else {
alert('Atleast one row should be there!')
}
}
<table id="tableInformation">
<tr>
<td>
<label>No</label>
</td>
<td>
<label>Facility</label>
</td>
<td>
<label>Currency</label>
</td>
<td></td>
</tr>
<tr id='toClone'>
<td>
<label>1</label>
</td>
<td>
<div id="facility">
<select id="facility1" name="facility">
<option value=""></option>
<option value="AL">AL</option>
<option value="BL">BL</option>
<option value="CL">CL</option>
</select>
</div>
</td>
<td>
<div id="currency">
<select id="currency1" name="currency">
<option value=""></option>
<option value="idr">IDR</option>
<option value="usd">USD</option>
<option value="aud">AUD</option>
<option value="jpy">JPY</option>
</select>
</div>
</td>
<td>
<input type="button" id="btnAddRows" value=" + " onclick='addRows()' />
<input type="button" id="btnRemRows" value=" - " onclick='removeRows(this)' />
</tr>
</table>
Try this:
add one line in your remove function -
table.rows[j].cells[1].childNodes[0].children[0].id = 'facility'+(j-1+1);
as
function removeRows(index) {
var i = index.parentNode.parentNode.rowIndex;
var table = document.getElementById('tableInformation');
var rowCount = table.rows.length;
var iteration = rowCount -1;
/*var numbers = iteration +1;*/
if(iteration == 1) {
alert("Cannot remove");
}else{
table.deleteRow(i);
//alert(iteration);
for(var j=1; j<iteration; j++) {
table.rows[j].cells[0].childNodes[0].id = 'number'+(j-1+1);
table.rows[j].cells[0].childNodes[0].textContent = (j-1+1);
table.rows[j].cells[1].childNodes[0].children[0].id = 'facility'+(j-1+1);
table.rows[j].cells[1].innerHTML.replace(/id="(.+)1"/,'id="$1' + rowCount + '"');
table.rows[j].cells[2].innerHTML.replace(/id="(.+)1"/,'id="$1' + rowCount + '"');
table.rows[j].cells[3].innerHTML.replace(/id="(.+)1"/,'id="$1' + rowCount + '"');
}
}
}
I created a table and borrowed a javascript function from http://www.fourfront.us/blog/store-html-table-data-to-javascript-array to retrieve the contents of the table the way I wanted to. It almost works, but for some reason I cannot access the value that the user inputs.
I have made a JS fiddle at http://jsfiddle.net/danielmdavies/4mu80x2L/1/
The code is also posted below. If I use "time_cutoff": $(tr).find('td:eq(2)').html() instead of "time_cutoff": $(tr).find('td:eq(2)').val(), I get the html code that is correct I believe.
This is the relevant html code:
<table id="cycler_table">
<tr>
<th>Cycle Step</th>
<th>Mode</th>
<th>Time Cutoff</th>
<th>Voltage Cutoff</th>
<th>Current Cuttoff</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='cyc_mode1'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff1' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff1' value='0'>
</td>
<td>
<input type='text' name='current_cutoff1' value='0'>
</td>
</tr>
<tr>
<td>2</td>
<td>
<select name='cyc_mode2'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff2' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff2' value='0'>
</td>
<td>
<input type='text' name='current_cutoff2' value='0'>
</td>
</tr>
<tr>
<td>3</td>
<td>
<select name='cyc_mode3'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff3' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff3' value='0'>
</td>
<td>
<input type='text' name='current_cutoff3' value='0'>
</td>
</tr>
<tr>
<td>4</td>
<td>
<select name='cyc_mode4'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff4' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff4' value='0'>
</td>
<td>
<input type='text' name='current_cutoff4' value='0'>
</td>
</tr>
</table>
<textarea id="tbTableValuesArray" name="tblValuesArray" rows="10"></textarea>
</div>
<p id="cyc_confirm">Waiting for Properties to be Confirmed
<button onclick="storeAndShowTableValues()">Send the Setup</button>
And the Javascript
$(document).ready(function () {
console.log("ready!");
storeAndShowTableValues();
});
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').val('TableData = \n' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#cycler_table tr').each(function (row, tr) {
TableData[row] = {
"cyc_mode": $(tr).find('td').eq(1).val(),
"time_cutoff": $(tr).find('td:eq(2)').val(),
"voltage_cutoff": $(tr).find('td:eq(3)').val(),
"current_cutoff": $(tr).find('td:eq(4)').val()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').val('JSON array: \n\n' + TableData.replace(/},/g, "},\n"));
}
function print_r(arr, level) {
var dumped_text = "";
if (!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++) level_padding += " ";
if (typeof (arr) == 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof (value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
}
return dumped_text;
}
This is probably super easy but for whatever reason I can't work out how to make it give me the values.
Any help would be awesome.
Try something like this to get the values:
TableData[row] = {
"cyc_mode": $(tr).find('select').val(),
"time_cutoff": $(tr).find('input:eq(0)').val(),
"voltage_cutoff": $(tr).find('input:eq(1)').val(),
"current_cutoff": $(tr).find('input:eq(2)').val()
};
You need to find the actual input and select elements to get their values.
Or better:
var elem = $(tr);
TableData[row] = {
"cyc_mode": elem.find('select').val(),
"time_cutoff": elem.find('input:eq(0)').val(),
"voltage_cutoff": elem.find('input:eq(1)').val(),
"current_cutoff": elem.find('input:eq(2)').val()
};
Which avoids recreating the jquery object four times.