What do I want : When the user focus out the field, i would like to add a string in the depending of an other . The are in a table and the problem is that i have to build the string depending of the size of the table.
It would be really nice if you give some documentations to help me because im a bit lost..
HTML :
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1"
class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value=""
size="35" length="35" maxlength="35" class="obligatoryAssemblage
nomAssemblage">
</td>
The Table : result in my computer
The jQuery/JS :
$(".nomAssemblage").focusout(function(){
addApresFixNomElement();
});
function addSuffixNomElement(){
// Parametres
var rowCount = $('#tableAssemblage tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix;
var id;
// Switch
switch (typElem)
{
case 'EDITION':
for(id=1; id<rowCount; id++){
Suffix = "[EDI ->" + id + "]";
$(".nomAssemblage").append(Suffix);
}
break;
case 'ENCART':
break;
case 'INCARTO':
break;
case 'INCPLUS':
break;
case 'OPP':
break;
case 'SUPPLEMENTS':
break;
}
}
The result i want : This is what i want exaclty
You could use
$("#nom_element_" + id).val($("#nom_element_" + id).val() + " " + Suffix);
as $().append() is to append elements (have also improved the logic as well):
$(".nomAssemblage").focusout(function() {
addSuffixNomElement();
});
function addSuffixNomElement() {
// Parametres
var rowCount = $('#tableAssemblage tbody tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix = "";
var id = 1;
// Switch
switch (typElem) {
case 'EDITION':
Suffix = "[EDI ->" + id + "]";
break;
case 'ENCART':
Suffix = "[ENC ->" + id + "]";
break;
case 'INCARTO':
//Suffix = "[INCA ->" + id + "]";
break;
case 'INCPLUS':
//Suffix = "[INCP ->" + id + "]";
break;
case 'OPP':
//Suffix = "[OPP ->" + id + "]";
break;
case 'SUPPLEMENTS':
//Suffix = "[SUP ->" + id + "]";
break;
}
for (id = 1; id < rowCount; id++) {
$("#nom_element_" + id).val($("#nom_element_" + id).val().replace(/\[.*?\]/, '') + " " + Suffix);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<tr>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1" class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value="" size="35" length="35" maxlength="35" class="obligatoryAssemblage nomAssemblage">
</td>
<tr>
</tbody>
</table>
Related
I am trying to add another dropdown list to my table that is dependable from my first dropdown list. I manage to add the first dropdown to each row but I am unable to create the second one .
In my example fiddle code on the col6 I want to create the new dropdown list using jquery (something like I already did with the first dropdown), but its options are dependet on the options from the first dropdown.For example, if in the first dropdown I choose a value "aaa" then in the second dropdown there will only be shown the options from the array "A" and so on. -
https://jsfiddle.net/Lqopej93/
I tried few codes but none of them worked out.
<html>
<head>
<title>Filtered CSV File</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="static/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.18/datatables.min.css"/>
</head>
<body>
<h1>
Filtered CSV FIle
</h1>
<br/>
<br/>
<div class="myButtons">
<input type="button" value="Add new row" class="btn btn-info" id="addRow">
<input type="button" value="Delete rows" id="delete-row" class="btn btn-info">
</div>
<br/>
<div class="table-responsive">
<table class="dataframe my_class" id="my_id">
<thead>
<tr style="text-align:right;">
<th> </th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
<th>col7</th>
<th>col8</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>row1</td>
<td>row1</td>
<td>row1</td>
<td></td>
<td>row1</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row1</td>
<td>row1</td>
</tr>
<tr>
<th>2</th>
<td>row2</td>
<td>row2</td>
<td>row2</td>
<td></td>
<td>row2</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row2</td>
<td>row2</td>
</tr>
<tr>
<th>3</th>
<td>row3</td>
<td>row3</td>
<td>row3</td>
<td></td>
<td>row3</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row3</td>
<td>row3</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
$(function(){
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
});
});
var A = ['A1','A2','A3'];
var B = ['B1','B2','B3'];
var C = ['C1','C2','C3'];
var D = ['D1','D2','D3'];
$("#addRow").click(function(){
$("#my_id").each(function(){
var tds='<tr>';
jQuery.each($('tr:last th', this), function(){
tds += '<th>' +'<input type="checkbox" name="record" tittle="Delete this row"></input>' + '</th>';
});
jQuery.each($('tr:last td', this), function(){
if($('select',this).length){
tds+= '<td>' + $(this).html() + '</td>';
}else{
tds+= '<td></td>';
}
});
tds+= '</tr>';
$('tbody',this).append(tds);
$('#my_id tbody tr:last').attr("contentEditable", true);
});
});
//for the columns that need to be imported with dropdowns create editable option - temporarlly
$(function() {
$("tr").each(function() {
$(this).find("td:eq(3), td:eq(4),td:eq(5)").attr("contentEditable", true);
});
});
//Find and remove selected table rows
$('#delete-row').click(function(){
var r = confirm('Are you sure you want to delete them all?');
$("tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
if(r == true){
$(this).parents("tr").remove();
}else{
return false;
}
}
});
});
$('table').on('change', 'select', function(){
var selVal = eval($(this).val().toUpperCase());
option = "";
select = "";
for(var i=0; i<selVal.length;i++){
option += '<option value="'+ selVal + '">' + selVal[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
console.log(option);
$(this).parent('td').nextAll('td').find('select').parent('td').empty().append(select);
});
You just copy the logic and exchange the Var-Names/-Values:
$(function(){
//---YOUR CODE----
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
//---SAME CODE - DIFFRENT VAR-NAMES---
var secondshortcut = ['a','b'];
var secondDDM = ['AAA','BBB'];
var option2 = "",
select2 = "";
for(var j=0; j<secondDDM.length;j++){
option2 += '<option value="'+ secondshortcut[j] + '">' + secondDDM[j] + '</option>';
}
select2 = '<select name="code">' + option2 + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
$(this).find("td:eq(5)").append(select2);
});
})
EDIT:
Make 2 dependant selects:
let optsA = ['A1','A2','A3'];
let optsB = ['B1','B2','B3'];
let optsC = ['C1','C2','C3'];
$('[name="s1"]').on('change', function () {
let val = $(this).val();
let opts;
let options = [];
if(val === 'a') {
opts = optsA;
} else if(val === 'b') {
opts = optsB;
} else {
opts = optsC;
}
for(let i = 0; i < opts.length; i++) {
options.push('<option value="' + opts[i] + '">' + opts[i] + '</option>');
}
$('[name="s2"]').html(options.join(''));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<select name="s1">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select name="s2"></select>
Now you can put the two things together by yourself :)
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>
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 have a table whereby people can add rows.
There is a select input in the table that when changed, changes the values in a second select field via ajax.
The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.
I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?
The HTML form is
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
<td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
<td><select name="asset[0][type]">
<option><?php echo $typeoption ?></option>
</select></td>
<td><select class="manuf_name" name="asset[0][manuf]">
<option><?php echo $manufoption ?></option>
</select></td>
<td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
<td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
<td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
<td><select id="site" name="asset[0][site]">
<option><?php echo $siteoption ?></option>
</select></td>
<td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
<td><select id="new_select" name="asset[0][contact]"></select></td>
<!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
<td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
<td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
<td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
The script I have is
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/,
function(str,p1) {
return '[' + (parseInt(p1,10)+1)+ ']'
})
})
return false;
});
});
$(document).ready(function() {
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last')
if ($last.is(':nth-child(2)')) {
alert('This is the only one')
} else {
$last.remove()
}
});
});
$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
$.ajax ({
type : 'post',
url : 'assetprocess.php',
data: {
get_option : $(this).val()
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
})
});
});
</script>
and the assetprocess.php page is
<?php
if(isset($_POST['get_option'])) {
//Get the Site Contacts
$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));
if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
$contactid = $contactrow['contact_id'];
$contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
$contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}
exit;
}
?>
The code is ugly as sin, but this is only a self-interest project at this stage.
Any assistance would be greatly appreciated.
Cheers,
J.
Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/
A few minor HTML changes:
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<td>
<select name="asset[0][type]">
<option>---</option>
<option>Type Option</option>
</select>
</td>
<td>
<select class="manuf_name" name="asset[0][manuf]">
<option>---</option>
<option>
Manuf Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="Serial #" name="asset[0][serial_num]">
</td>
<td>
<input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
</td>
<td>
<input type="text" placeholder="Name or Description" name="asset[0][description]">
</td>
<td>
<select id="site-0" class="chooseSite" name="asset[0][site]">
<option>---</option>
<option>
Site Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
</td>
<td>
<select id="new-site-0" name="asset[0][contact]">
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
});
var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
newId = lastId + 1;
$("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
$("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
return false;
});
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last');
if ($last.is(':nth-child(2)')) {
alert('This is the only one');
} else {
$last.remove();
}
});
$(".chooseSite").change(function(event) {
console.log($(this).attr("id") + " changed to " + $(this).val());
var target = "new-" + $(this).attr('id');
/*$.ajax({
type: 'post',
url: 'assetprocess.php',
data: {
get_option: $(this).val()
},
success: function(response) {
$("#" + target).html(response);
}
});*/
var response = "<option>New</option>";
$("#" + target).html(response);
});
});
Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/
function cloneRow(n) {
if (n - 1 < 0) return false;
var html = "";
html += "<tr class='removable' data-row=" + n + ">";
html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
html += $("#type-" + (n - 1)).html();
html += "<select></td>";
html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
html += $("#manuf-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
html += $("#site-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
html += "</tr>";
return html;
}
It's more work up front, yet offers a lot more control of each part. And much easier to use later.