I have a webpage that based on user input populates with form fields, as done by the following:
function Go2() {
var loans = document.getElementById('count').value;
var content = document.getElementById('stage3').innerHTML;
content = '<TABLE Width="100%">'
+'<TR>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Name</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Number</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Origination Date</TD>'
+'</TR>'
+'</TABLE>';
document.getElementById('stage3').innerHTML = content;
for(var i=0; i<loans; i++) {
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE Width="100%">'
+ '<TR>'
+ '<TD Width="30%"><INPUT Name="CName'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="CNumber'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="Date'
+ i
+ '" Size="40" Type="text"></TD>'
+ '</TR>'
+ '</TABLE>';
}
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE><TR><TD><INPUT Type="Button" Value="Submit" onClick="Go3()"></TD></TR></TABLE>';
}
Now what I need to do is iterate through the form and pull out the values for each of the form fields. This is about as far as I've gotten:
for (var n=0; n<loans; n++) {
content += '<TR>'
+ '<TD Colspan="2">'
+ document.getElementById('CName + n').value
+ '</TD>'
+ '<TD Colspan="2">'
+ document.getElementById('CNumber + n').value
+ '</TD>'
+ '<TD>'
+ document.getElementById('Date + n').value
+ '</TD>'
+ '</TR>';
}
Which does...Nothing. The last notable progress I had was getting it to spit out "null" which isn't really progress at all. I've looked at eval, but there's quite a few warnings against it.
Any Ideas?
I think you want
document.getElementById('CName' + n).value
(where n is outside of the quotes)
Well it should be 'CName' + n - i.e., you got the quotation marks in the wrong place
If all your controls are in a form, then you can access them as:
var allControls = document.<formId>.elements;
or
var allControls = document.forms[formId].elements;
Then iterate over the list of controls to get the values. The form controls must have names to be successful, no need for IDs. You can also get the values as:
var value = allControls['CName' + n].value;
or just
var form = docment.forms[formID];
var value = form['CName' + n].value;
Related
I'm trying to insert a button in the end of each row of the table receitas but the buttons are being set at the start of the table instead of the end of each row.
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for(let i in receitas) {
if(receitas[i].tipo==aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> '+ receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td></td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
The line where I put all the properties into the table row (inside of for), I have an input which should be set at the end of the row but instead, it is going to the top of the table.
It's just a type error in the cell wrapping the button you're creating </td> instead of starting <td>
see belown snippet :
receitas = [
{tipo:"typ1",nome:"nome1",tempo:"tempo1",custo:"custo1",dificuldade:"dificuldade1"},
{tipo:"typ2",nome:"nome2",tempo:"tempo2",custo:"custo2",dificuldade:"dificuldade2"},
{tipo:"typ1",nome:"nome3",tempo:"tempo3",custo:"custo3",dificuldade:"dificuldade3"},
{tipo:"typ1",nome:"nome4",tempo:"tempo4",custo:"custo4",dificuldade:"dificuldade4"},
]
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for (let i in receitas) {
if (receitas[i].tipo == aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> ' + receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td><td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
mostraTabelaTeste("typ1","table");
<div id="table"></div>
You may need to add one more th for button column in first row. Like below:
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th><th> </th></tr>';
I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td
I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a <tr></tr> and I dont have that on javascript.
I just want a table with 3 columns and up to 10 rows.
What's happening?
My generated html
JavaScript
$('#selectMRPC').change(function () {
//fetch data
var mrpc = $(this).find('option:selected').data('mrpc');
$('#paramBody').empty();
for (var i = 1; i <= 10; i++) {
var field = mrpc["field" + i];
if (field !== undefined) {
var parsedField = field.split('_');
var value = parsedField[0];
var type = parsedField[1];
switch (type) {
case "S":
type = "text";
if (value === '""')
value = null;
break;
case "B":
type = "checkbox";
break;
case "N":
type = "number";
value = parseInt(value);
break;
case "D":
type = "number";
value = parseInt(value);
if (value === '""')
value = null;
break;
}
$('#paramBody').append('<tr>');
$('#paramBody').append('<td>' + i + '</td>');
$('#paramBody').append('<td>' + type + '</td>');
$('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
$('#paramBody').append('</tr>');
}
}
});
store everything in a var then add it to dom :
var html = "";
html += '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value +'">';
html += '</tr>';
$('#paramBody').append(html);
You are appending everything to #paramBody, which is incorrect. Consecutively, you need to append/insert data into <tr>. So I would recommend, you concatenate everything together instead of appending.
You need to change
$('#paramBody').append('<tr>');
$('#paramBody').append('<td>' + i + '</td>');
$('#paramBody').append('<td>' + type + '</td>');
$('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
$('#paramBody').append('</tr>');
to
var rowHtml = '<tr>' + '<td>' + i + '</td>' + '<td>' + type + '</td>' + '<td><input name="Fields" type="' + type + '">' + value + '</tr>';
$('#paramBody').append(rowHtml);
append will create an element from the parameter if the given input is not already a valid html string
Make it
$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input name="Fields" type="' + type + '" value="' +value + '"></tr>');
Or append them one by one (example below)
$( "<tr></tr>" ).append('<td>' + i + '</td>').appendTo( '#paramBody' );
Or create a string first
var html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value + '">';
html += '</tr>';
$('#paramBody').append(html );
I have a button that when I click on it, it dynamically generates rows in the table, it also generates a button to remove that row.
The problem I have is every time a row is generated, the value of a cell is summed in a text field, and when I remove that row I need to subtract the value from that cell to my text field.
That is why I need to get the value of that cell when it is removed.
This is my button tha generates the dynamic row in the table:
<input type="button" name="agregar" id="agregar" value="Agregar" class="btn btn-primary"/>
And this is the jQuery code for the click event of the button:
$("#agregar").click(function () {
var productoId = $("#productoId").val();
var productoDescripcion = $("#productoDescripcion").val();
var productoPrecio = $("#productoPrecio").val();
var productoCantidad = $("#productoCantidad").val();
var productoIva = $("#productoIva").val();
total = (productoPrecio * productoCantidad) - (((productoPrecio * productoCantidad) * productoIva) / 100);
subTotal = subTotal + total;
$("#totalAPagar").val(subTotal);
var presupuesto = '<tr>' +
'<td>' + productoId + '</td>' +
'<td>' + productoDescripcion + '</td>' +
'<td>' + productoPrecio + '</td>' +
'<td>' + productoCantidad + '</td>' +
'<td>' + productoIva + '</td>' +
'<td>' + total + '</td>' +
'<td class="eliminar-fila"><button id="eliminar" class="btn btn-danger eliminar" type="button"><span class="fa fa-remove"></span></button></td>' +
'</tr>';
$("#presupuestoDetalle tbody").append(presupuesto);
$(".eliminar").click(function () {
valor = $(this).find("td").eq(5).text();
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
subTotal = subTotal - valor;
$("#totalAPagar").val(subTotal);
});
});
});
Inside this event click I have another event click on the "delete" button, which is the one in charge of removing the row. In this event click I want to get the value of the "total" cell like this:
valor = $(this).find("td").eq(5).text();
In order to be able to do this arithmetic operation:
subTotal = subTotal - valor;
But the field valor is in blank. How can i get the value of that cell?
I built a minimal verifiable sample here and found a few little points on the way:
You are assigning the click event listener for ".eliminar" potentially several times, when there are more than one lines in your table.
I changed that to a single assignment using .on().
Your valor was determined wrongly. It needs to be something like
valor = $(this).closest('tr').find("td").eq(5).text();
var subTotal=0,total=0;
$(function(){
$("#agregar").click(function(){
var productoId = $("#productoId").val();
var productoDescripcion = $("#productoDescripcion").val();
var productoPrecio = $("#productoPrecio").val();
var productoCantidad = $("#productoCantidad").val();
var productoIva = $("#productoIva").val();
total = (productoPrecio * productoCantidad) - (((productoPrecio * productoCantidad) * productoIva) / 100);
subTotal = subTotal + total;
$("#totalAPagar").val(subTotal);
var presupuesto = '<tr>' +
'<td>' + productoId + '</td>' +
'<td>' + productoDescripcion + '</td>' +
'<td>' + productoPrecio + '</td>' +
'<td>' + productoCantidad + '</td>' +
'<td>' + productoIva + '</td>' +
'<td>' + total + '</td>' +
'<td class="eliminar-fila"><button class="btn btn-danger eliminar" type="button">eliminar</button></td>' +
'</tr>';
$("#presupuestoDetalle tbody").append(presupuesto);
});
$('tbody').on("click",".eliminar",function(){
valor = $(this).closest('tr').find("td").eq(5).text();
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
subTotal = subTotal - valor;
$("#totalAPagar").val(subTotal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="productoId" name="productoId" value="123"/> id<br/>
<input type="text" id="productoDescripcion" name="productoDescripcion" value="producto A"/> descr.<br/>
<input type="text" id="productoPrecio" name="productoPrecio" value="10" /> precio<br/>
<input type="text" id="productoCantidad" name="productoCantidad" value="3" /> cant.<br/>
<input type="text" id="productoIva" name="productoIva" value="19" /> iva
<input type="text" id="totalAPagar" name="totalAPagar" value="0"><br/>
<input type="button" name="agregar" id="agregar" value="Agregar" class="btn btn-primary"/>
<table id="presupuestoDetalle">
<tr><th>Id</th><th>Descripcion</th><th>Precio</th><th>Contidad</th><th>Iva</th><th>total</th></tr>
</table>
I forgot to put the .parents("tr") method in the expression like this:
valor = $(this).parents("tr").find("td").eq(5).html();
I suppose I did not find the 'td' selector before, so first I have to go to the parent selector with .parents ('tr') and then try to find the 'td' selector, and then i put the html() method instead of the .text() method.
Now I can get the value of the cell.