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 :)
Related
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>
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 + '"');
}
}
}
How can I change the number of rows and columns of a html table with the input text, based on the value selected in the select Id option?
like
Number of Models : 1,2,3,4
Number of items per Model :(this is the table that takes the input values and this needs to change the number of rows or columns of the table based on the value selected in the 'Number of Models'), this is the code i have:
<table>
<tr>
<th>Number of Models:<title="Number of Models"></th>
<td><select id="numberofmodels" onkeyup="NumberOfModels()" name="Number of Models">
<option >1</option >
<option >2</option >
<option >3</option >
<option >4</option >
<option >5</option >
<option >6</option >
</select></td>
</tr>
<tr>
<th>Number of items per model:</th>
<td>
<table border="1">
<tr>
<td>
<input id="itemsmodel" onkeyup="ItemsModelValidate()" type="text" maxlength="50" > <br>
</td>
</tr>
</table>
can somebody give me the javascript function ItemsModelValidate() to make this work ?
I have the following javascript function for other purpose, can this be edited to achieve that ?
function ItemsModelValidate(){
$itemsmodel = document.getElementById("itemsmodel").value;
if(!/^[0-9]+$/.test($itemsmodel)) {
alert();
}
}
function NumbersOfModels(){
$numberofmodels = document.getElementById("numberofmodels").value;
if(!/^[0-9]+$/.test($numberofmodels)) {
alert();
}
}
You can use something like this:
<html>
<body>
<table>
<tr>
<th>Number of Models:</th>
<th>
<select id="NumberOfModels" name="Number of Models">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</th>
</tr>
<tr>
<th>Number of items per model:</th>
</tr>
<tr>
<td>
<table border="1">
<tbody id="itemsmodel"></tbody>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
var models = document.getElementById("NumberOfModels");
var modelsTable = document.getElementById("itemsmodel");
models.addEventListener("change", drawModels, false);
function drawModels(){
var modelsNum = parseInt(models.value);
var curModels = modelsTable.rows.length;
if (modelsNum > curModels) {
var delta = modelsNum - curModels;
for(var i = 0; i < delta; i++) {
var rowElement = document.createElement("tr");
var cellElement = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("maxlength", "3");
input.addEventListener("keyup", drawItems, false);
cellElement.appendChild(input);
rowElement.appendChild(cellElement);
modelsTable.appendChild(rowElement);
}
} else {
while(modelsTable.rows.length > modelsNum){
var row = modelsTable.rows[modelsTable.rows.length - 1];
modelsTable.removeChild(row);
}
}
}
function drawItems(){
var row = this.parentNode.parentNode;
var val = this.value;
var isNum = /^\d+$/.test(val);
if(isNum){
var curCells = row.cells.length - 1;
var cellsNum = parseInt(val);
if(cellsNum > curCells){
var delta = cellsNum - curCells;
for(var i = 0; i < delta; i++) {
var cellEl = document.createElement("td");
cellEl.innerText = "Lorem ipsum";
row.appendChild(cellEl);
}
} else {
while(row.cells.length > cellsNum + 1) {
var cell = row.cells[row.cells.length-1];
row.removeChild(cell);
}
}
}
}
drawModels();
</script>
</body>
</html>
I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}