Disable fields of a select in html with JS [duplicate] - javascript

This question already has an answer here:
Problem disable fields of a select in html with JS
(1 answer)
Closed 1 year ago.
I try to disable a field when an option is chosen in a select. I have created a script with a function in JS to disable it, more however it does not work. Any ideas what to do?
When I select "T in% compared to the previous day", I need the "Time /%" field to be disabled, which I have not achieved.
So the code I have implemented for the select is this:
<tr>
<td color="#66ccff"><strong>Patrón 1 (<select name="TipoPatron1" id="TipoPatron1">
<option value="00" selected="selected">T desde el encendido</option>
<option value="01">T desde las 12:00</option>
<option value="10" onclick="desactivar()">T en % respecto día anterior</option>
</select>
)</strong></td>
</tr>
<tr>
<td>
<table border="0">
<tbody>
<tr color="#ccff00" align="center">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</tbody>
</table>
</td>
</tr>
Here I create the selectable menu with the fields they will have and then through a script I pass it to fill the fields and I also create the function to disable the "Hours" boxes
<script language="javascript">
var I = 1;
for (I = 1; I <= 8; I++) {
document.writeln("<tr align=center>");
document.writeln("<td>"+I+" <input type=\"checkbox\" checked id=\"AP1C"+I+"\"></td>");
document.writeln("<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP1C"+I+"\" maxlength=3 size=3></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"MP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("<td><select name=\"dimado\" id=\"DP1C"+I+"\"><option value =\"0\">0%</option><option value =\"1\">1%</option><option value =\"2\">2%</option><option value =\"3\">3%</option><option value =\"4\">4%</option><option value =\"5\">5%</option><option value =\"6\">6%</option><option value =\"7\">7%</option><option value =\"8\">8%</option><option value =\"9\">9%</option><option value=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"IP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"CP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("</tr>");
}
function alerta() {
alert("Seguro que quieres actualizar?");
}
function desactivar() {
document.getElementById('HP1C').setAttribute("disabled", "disabled");
}
</script>
In the desactivar() function, I try to pass with the ID of the HP1C element representing the hours ID, I pass the getElementByID and the disable attribute, but it doesn't work.
In the photo, when you see the "Patron1" select with "T en % respecto al dia anterior" The "Hora/%" field must be deactivated

disabled is a boolean attribute.
function desactivar() {
for (let i = 0; i < 8; i++)
document.getElementById('HP1C1'+i).setAttribute("disabled", true);
}
Edit: You don't use the right event
<body>
<h1>Patrón 1</h1>
<select name="TipoPatron1" id="TipoPatron1">
<option value="00" selected="selected">T desde el encendido</option>
<option value="01">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody">
</tbody>
</table>
<script language="javascript">
let i = 1;
let tbody = document.querySelector("#mytbody");
for (let i = 1; i <= 8; i++) {
tbody.innerHTML += "<tr>";
tbody.innerHTML += "<td>"+i+" <input type=\"checkbox\" checked id=\"AP1C"+i+"\"></td>";
tbody.innerHTML += "<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP1C"+i+"\" maxlength=3 size=3></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"MP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "<td><select name=\"dimado\" id=\"DP1C"+i+"\"><option value =\"0\">0%</option><option value =\"1\">1%</option><option value =\"2\">2%</option><option value =\"3\">3%</option><option value =\"4\">4%</option><option value =\"5\">5%</option><option value =\"6\">6%</option><option value =\"7\">7%</option><option value =\"8\">8%</option><option value =\"9\">9%</option><option value=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"iP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"CP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "</tr>";
}
const select = document.querySelector('#TipoPatron1')
select.onchange = () => {
if (select.value == '10') {
desactivar()
}
}
function alerta() {
alert("Seguro que quieres actualizar?");
}
function desactivar() {
for (let i = 1; i<= 8; i++)
document.getElementById('HP1C' + i).setAttribute("disabled", "disabled");
}
</script>
</body>

Related

Problem disable fields of a select in html with JS

I try to disable a field when an option is chosen in a select. I have created a script with a function in JS to disable it, more however it does not work. Any ideas what to do? When I select "T in% compared to the previous day", I need the "Time /%" field to be disabled, which I have not achieved.
So the code I have implemented for the select is this
Here I create the selectable menu with the fields that they will have and then through a script I pass it to fill the fields and I also create the function to disable the "Hours" boxes. So, here the problem arises, inside the script when const select = document.querySelector (# 'TipoPatron2') is started The table disappears, more however when the query selector is commented the table is still there
<table border="0">
<body>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label>
</td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
<script language="javascript">
let tbody2 = document.querySelector("#mytbody2");
var I = 1;
for (I = 1; I <= 8; I++) {
document.writeln("<tr align=center>");
document.writeln("<td>" + I + " <input type=\"checkbox\" checked id=\"AP2C" + I + "\"></td>");
document.writeln("<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP2C" + I + "\" maxlength=3 size=3></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"MP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><select name=\"dimado\" id=\"DP2C" + I + "\"><option value =\"0\">0%</option><option value =\"1\">1%</option><option value =\"2\">2%</option><option value =\"3\">3%</option><option value =\"4\">4%</option><option value =\"5\">5%</option><option value =\"6\">6%</option><option value =\"7\">7%</option><option value =\"8\">8%</option><option value =\"9\">9%</option><option value=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"IP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"CP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("</tr>");
}
//Creo una selector para que valide si se selecciona la opción de "T%" se ejecute la función desactivar
/*const select = document.querySelector('#TipoPatron2')
select.onchange = () => {
if (select.value == '10') {
desact()
}
}
*/
//Se crea la función alerta para cuando se haga un pegado en los box se ejecute la alerta
function alerta() {
alert("Seguro que quieres actualizar?");
}
//Se crea una función desactivar que se efectua en un for de 0 a 8 con el ID de las horas
function desact() {
for (let i = 1; i <= 8; i++)
document.getElementById('HP2C' + i).setAttribute("disabled", "disabled");
}
</script>
<tr align="center">
</tbody>
</table>
</body>
</td>
Photos when when queryselector is not commented
Now, I go to the page and the table disappears enter image description here
And if I comment the const select = document.querySelector ('# TipoPatron2') the table appears enter image description here
I need this query selector, since this is in charge of disabling the "Hora/%" when "T en % respecto día anterior" is selected in the first select. Any ideas what to do pls?
Have a look at this
I made the creation of the select simpler
I assume you mean to disable the HP2Cs when TipoPatron2 have value "10"
const tbody2 = document.getElementById("mytbody2");
tbody2.innerHTML = Array.from({length: 8}, (_, index) => index + 1).map(i => `<tr align=center>
<td>${i}<input type="checkbox" checked id="AP2C${i}" /></td>
<td><input type="text" value="0" id="HP2C${i}" maxlength=3 size=3 /></td>
<td><input type="text" value="0" id="MP2C${i}" maxlength=2 size=2 /></td>
<td><select name="dimado" id="DP2C ${i}">${Array.from({length: 29}, (_, index) => index + 1).map(i => `<option value="${i}">${i}%</option>`).join("") }
<option value = "31">100%</option></select></td>
<input type="text" value="0" id="IP2C${i}" maxlength=2 size=2 /></td>
<td><input type="text" value="0" id="CP2C${i}" maxlength=2 size=2 /></td>
</tr>`).join("")
const HP2Cs = document.querySelectorAll("[id^=HP2C]")
document.getElementById("TipoPatron2").addEventListener("change", function() {
const dis = this.value==="10";
HP2Cs.forEach(hp2c => hp2c.disabled = dis)
})
tbody2.addEventListener("paste", e => {
const tgt = e.target;
if (tgt.id.startsWith("HP2C")) alert("Seguro que quieres actualizar?");
})
<table border="0">
<tbody>
<tr>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label></td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

how to get user entered data and ID's in dynamically added table rows?

How can I get dynamically added rows id's and user entered data? I have created a dynamic table but I don't know how to get the values and dynamically generated id's. Can anyone please help me?
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if (!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><select class="form-control" id=' + cashacc + ' ' + FieldCount + '></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' ' + FieldCount + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" data-action="sumDebit" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' ' + FieldCount + '/></td><td style="width: 4%"><img src="./img/delete.svg" class="dlt-icon" ' + FieldCount + '></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row" class="jsrow">
<!-- First row -->
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control narate" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" data-action="sumDebit" value="100" class="form-control" name="cashdeb" readonly/>
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly/>
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
</tbody>
</table>
FIDDLE Here..
What do you mean by ids?? on what action you would want user data and ids of dynamically created rows.
Everything is there. You have jsrow enter code hereclass for each tr created. Fetch all tr and then fetch each input value as you have distinct class for each input.
var rows = $('#cashTable').find('tr.jsrow'); // get all rows.
Then iterate rows as per your need. i am writing directly lets say want to get all ids of row 2. Find all inputs under that row as below and then get id attribute.
var inputs = $(rows[0]).find('input'); // all inputs. same way all select as well
// iterate all inputs and grab ID attribute
for(let i =0 ; i< inputs.length; i++ ) {
var attr = inputs[i].getAttribute('id');
console.log(attr); // id attribute
console.log(inputs[i].value); // value
}
You can get user input by referring to the column and row inside a table
var table = document.getElementById("cashTable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseFloat(table.rows[i].cells[5].innerHTML);
//here cells is referred to the cell number you want the value if you want the value of all cells of a row then loop through the cells of a row
}
alert(sumVal);
console.log(sumVal);

How to take value from cell in javascript

I have a grid setter in javascript like this :
function AddMdrPymt(){
var f = document.frmPL0011;
var grid = document.getElementById("mdrPymtGrid");
var numRows = grid.rows.length;
grid.insertRow(numRows);
grid.rows[numRows].insertCell(0);
grid.rows[numRows].insertCell(1);
grid.rows[numRows].insertCell(2);
grid.rows[numRows].insertCell(3);
grid.rows[numRows].cells[0].innerHTML = "<input type='checkbox' value='" + curRow + "' name='__mdrPymt' id='__mdrPymt'>";
grid.rows[numRows].cells[1].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_strtAmnt' id='txt_strtAmnt' class='" + txtclass + "' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanStartAmnt", true)%>' onblur='checkData(this)' value = '" + val + "' "+dsb+"></td></tr></table>";
grid.rows[numRows].cells[2].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_endAmnt' id='txt_endAmnt' class='portlet-form-input-field' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanEndAmnt", true)%>' onblur='checkData2(this)'></td></tr></table>";
curRow += 1;
And this is the grid HTML, the HTML code for the grid tittle, and the function above is function when user press add button
<table width="95%" align="center">
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="4">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="5">
</td>
</tr>
<tr>
<td>
<table border="0" cellspacing="1" cellpadding="1" name="mdrPymtGrid" id="mdrPymtGrid" class="grid" width="95%">
<thead class="header">
<th width="1%"></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanStartAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanEndAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixAmntInd",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixCashAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_CashbackLoanAmnt",true)%></th>
</thead>
</table>
</td>
</tr>
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="6">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="7">
</td>
</tr>
</table>
How to get value from txt_strtAmnt ?
Thank you
Please use the below code snippet to get the TABLE > TR > TD HTML elemnt value : -
/* To get any TD element value. If one input type inside TD element.
No need to mention the id name as we are getting the value using Tag Name. */
var grid = document.getElementById("mdrPymtGrid");
var tableRows = grid.getElementsByTagName("tr");
for (var j = 0 ; j <= tableRows.length; j++){
var tds = tableRows[j].getElementsByTagName("td");
for (var k = 0 ; k <= tds.length; k++){
var strtAmntVal = tds[k].getElementsByTagName('input')[0].value;
break;
}
}
If you are using grid with multiple rows then solution provided by #Arun will not work,
To make it work
1)find grid element first with document.getElementById('gridid');
2)iterate through its children
3)in that iteration loop find document.getElementById('txt_strtAmnt').value
I am sure that will help you !
also we can achieve through JQuery if you want

Form last value removed after add another field with Javascript

In my html form I can add extra fileds with javascript. But problem is it's removed the last submitted value when I add another field.
For example:
There is a form fileds called: Ingredient and Quantity. I can add another ingredient and Quantity field by click on "Add more" buttion. Ok suppose, I added a new fields and wrote it's value. But if I again click on the "Add more" buttion it's deleted my last fields value.
**Add more = (Ajouter un autre ingrédient)
Html Code:
<table width="700" border="0" cellspacing="0" cellpadding="5" class="table" style="float:">
<td width="180">Ingrédients</td>
<td>
<input type="text"class="tr" name="ingredients[]" id="ingredients" placeholder="Ingredient"/>
</td>
</tr>
<tr>
<td>Quantité</td>
<td><input name="quantity[]" type="text" id="quantity" placeholder="Quantity" class="tr" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" onclick="addmyrow()" name="add" value="Ajouter un autre ingrédient" /><br/><br/> <div id="row"></td>
</tr>
</table>
Javascript Code:
<script language="javascript">
fields = 0;
function addmyrow() {
if (fields != 10) {
document.getElementById('row').innerHTML += "<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient'/><br/>";
document.getElementById('row').innerHTML += "<input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>";
fields += 1;
} else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
Thanks.
When you append contents like this: document.getElementById('row').innerHTML += ...
you're technically replacing the innerHTML with new HTML.
This causes any changes (i.e., form value changes) to be erased.
The correct way is to create brand new DOM elements and then append those elements. What you're doing now is just appending additional HTML.
Here's the corrected version:
<table width="700" border="0" cellspacing="0" cellpadding="5" class="table" style="float:">
<tr>
<td width="180">Ingrédients</td>
<td>
<input type="text"class="tr" name="ingredients[]" id="ingredients" placeholder="Ingredient"/>
</td>
</tr>
<tr>
<td>Quantité</td>
<td><input name="quantity[]" type="text" id="quantity" placeholder="Quantity" class="tr" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" onclick="addmyrow()" name="add" value="Ajouter un autre ingrédient" /><br/><br/> <div id="row"></div>
</td>
</tr>
</table>
<script language="javascript">
fields = 0;
function addmyrow() {
if (fields != 10) {
var newIngredients = document.createElement('input');
var newQuantity = document.createElement('input');
var brTag = document.createElement('br');
newIngredients.setAttribute('type', 'text');
newQuantity.setAttribute('type', 'text');
newIngredients.setAttribute('placeholder', 'Ingredient');
newQuantity.setAttribute('placeholder', 'Quantity');
newIngredients.setAttribute('name', 'ingredients[]');
newQuantity.setAttribute('name', 'quantity[]');
newIngredients.setAttribute('class', 'tr');
newQuantity.setAttribute('class', 'tr');
document.getElementById('row').appendChild(newIngredients);
document.getElementById('row').appendChild(brTag);
document.getElementById('row').appendChild(newQuantity);
document.getElementById('row').appendChild(brTag);
fields += 1;
} else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
And here's a working fiddle: http://jsfiddle.net/tC7Dm/
changes in innerHTML causes all child DOMs to be destroyed. this link might help
Is it possible to append to innerHTML without destroying descendants' event listeners?
here you go, whoever minusoned me deserves a spoonful of feed.
<script>
function addmyrow() {
var mydiv = document.getElementById("row");
var newcontent = document.createElement('div');
newcontent.innerHTML = "<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient'/><br/><input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>";
if (fields < 10) {
while (newcontent.firstChild) {
mydiv.appendChild(newcontent.firstChild);
}
fields=fields+1;
}
else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
#Babu, the reason behind this issue is when you get the existing value with innerHTML it doesn't get the value for input dom elements because the value stored in the property not in the attribute. You could find the same in following links
Inner HTML with input values
So rather than using JS you could try jQuery, Below is a working demo
var fields = 0;
function addmyrow() {
if (fields != 10) {
$("#row").append("<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient' value='' /><br/>");
$("#row").append("<input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>");
fields += 1;
}
else {
$("#row").append("<br />Only 10 upload fields allowed.");
document.form.add.disabled=true;
}
}
Fiddle Demo

How to collect values (data) of dynamically added rows (HTML table) ? Using php & XAMPP

I created a simple form with a dynamic table. This table rows increment by the user input values, so I need to increment the combo box or the select (option) every time a new row created, so it should be like default combo box values. Note: this select or combo box is part of the column attributes, remember the rows increment, but without the column.
2nd Question:
I want to collect this table columns data or values whatever its rows number is, and store it to XAMPP database using php. I know how to collect data from a single form, but I don't know how to collect data from dynamic form.
Here is the code:
function AddRows()
{
var tableelement = document.getElementById("mytable")
var rows = document.getElementById("noofrows").value;
var tablerowcount = tableelement.rows.length;
var currowcount = tablerowcount;
for(i = 1; i < rows; i++) {
var row = tableelement.insertRow(currowcount);
var cellid = row.insertCell(0);
cellid.innerHTML = "<b>" + currowcount +"</b>";
var cellid2 = row.insertCell(1);
cellid2.innerHTML = "<input value='' id='" + currowcount +"_name' /> ";
var cellid3 = row.insertCell(1);
cellid3.innerHTML = "<input value='' id='" + currowcount +"_name' /> ";
var cellid4 = row.insertCell(1);
cellid4.innerHTML = "<input value='' id='" + currowcount +"_name' /> ";
var cellid5 = row.insertCell(1);
cellid5.innerHTML = "<input value='' id='" +currowcount +"_name' /> ";
var cellid6 = row.insertCell(1);
cellid6.innerHTML = "<input value='' id='" +currowcount+"_name' /> ";
var currowcountcurrowcount = currowcount++;
}
}
</script>
</head>
<body>
<form method="post" action="insert.php>
Carton Number :<input type="text" name="cn"> <br>
Business Unit :<input type="text" name="bu"> <br>
No of Files :<input type="noofrows" id="noofrows" value="1" name="nof" />
<input name="add" id="add" type="button" value="Add" onClick="AddRows()"/>
<table name="mytable" id="mytable" border=1>
<tr>
<td>
<b>SN</b>
</td>
<td>
<b>From</b>
</td>
<td>
<b>To</b>
</td>
<td>
<b>Range</b>
</td>
<td>
<b>Document Category</b>
</td>
<td>
<b>Document Type</b>
</td>
</tr>
<tr>
<td>
<b>1</b>
</td>
<td>
<input value="" id='1_name' >
</b>
</td>
<td>
<input value="" id='1_name'/>
</b>
</td>
<td>
<input value="" id='1_name' />
</b>
</td>
<td>
<Select id='select' />
<option name="option" value="finance">Finance Documents</option>
<option name="option" value="hr">HR Documents</option>
<option name="option" value="test">test</option
</Select>
</b>
</td>
<td>
<Select id='select' />
<option name="option" value="CP">Cash movement</option>
<option name="option" value="PV">Payment Voucher</option>
<option name="option" value="RV">RV</option
</Select>
</b>
</td>
</tr>
</table>
<br/>
function AddRows()
{
var tableelement = document.getElementById("mytable")
var rows = document.getElementById("noofrows").value;
var tablerowcount = tableelement.rows.length;
var currowcount = tablerowcount;
for(i = 1; i < rows; i++) {
var row = tableelement.insertRow(currowcount);
var cellid = row.insertCell(0);
cellid.innerHTML = "<b>" + currowcount +"</b>";
var cellid2 = row.insertCell(1);
cellid2.innerHTML = "<Select id='select' /><option name='option' value='CP'>Cash movement</option><option name='option' value='PV'>Payment Voucher</option> <option name='option' value='RV'>RV</option></Select> ";
var cellid3 = row.insertCell(1);
cellid3.innerHTML = "<Select id='select' /><option name='option' value='finance'>Finance Documents</option><option name='option' value='hr'>HR Documents</option><option name='option' value='test'>test</option</Select> ";
var cellid4 = row.insertCell(1);
cellid4.innerHTML = "<input value='' id='" + currowcount +"_name' /> ";
var cellid5 = row.insertCell(1);
cellid5.innerHTML = "<input value='' id='" +currowcount +"_name' /> ";
var cellid6 = row.insertCell(1);
cellid6.innerHTML = "<input value='' id='" +currowcount+"_name' /> ";
var currowcountcurrowcount = currowcount++;
}
}
</script>
change in your function to get the selection for every row
and to save data first you change the all inputs and selections id as array variable
ex id='1_name_Range[]'for range. also change in the function
renaming code for save you know well as you say.used the array variable to save in database

Categories