2011-09-20 22 views
5

enter image description here¿Cómo se suman los valores del campo de entrada y se muestran en la tabla html usando Javascript?

Soy nuevo en Javascript, por favor ayuda para resolver este problema Expertos en Javascript. Tengo un formulario de registro que tiene estos campos anteriores. De esta forma, cuando hago clic en "Agregar nueva línea de registro", insertará un nuevo campo de inserción como el anterior. A partir de estos, deseo agregar estos valores de campos de entrada resaltados y mostrarlos en la tabla html. Cuando marque la casilla de verificación, los valores se mostrarán en el campo de invocación. Del mismo modo, cuando desactive la casilla de verificación, los valores se mostrarán en el campo No Vocabulario. Me refiero a que la suma de los valores verificados debe mostrarse en el campo Invoicable y la suma de los valores no verificados debe mostrarse en el campo Non-invoicable. Esta es la parte de código del tema que estoy tratando:

<script type="text/javascript"> 
$(function() { 
var i = 8 + 1; 
$('input#add').click(function() { 
//store in hidden value for total row 
document.getElementById("consinvoice").value=i; 

$("<span style='margin-left:126px;'>:&nbsp;<select name='RegistrationType_"+i+"' id='RegistrationType_"+i+"' onchange=\"register('Invoicable_"+i+"',this.value,ConsultancyHours_"+i+".value)\"><option value='CH'>Consultancy Hours</option><option value='LH'>Lunch Hours</option><option value='TH'>Transportation Hours</option><option value='OH'>Other Hours</option></select>&nbsp;<input name='ConsultancyHours_"+i+"' type='text' id='ConsultancyHours_"+i+"' size='5' onkeyup=\"invotable(this.id,this.value);\" /><label for='Hourprice'> Std. Hourprice</label>&nbsp;<input name='Hourprice_"+i+"' type='text' id='Hourprice_"+i+"' size='5' />&nbsp;<label for='Hourprice'>- Discount Hourprice</label>&nbsp;<input name='Hourprice2_"+i+"' type='text' id='Hourprice2_"+i+"' size='5' /><br /><span style='margin-left:652px;'><input name='Invoicable_"+i+"' type='checkbox' id='Invoicable_"+i+"' checked='checked' onclick=\"register('Invoicable_"+i+"',RegistrationType_"+i+".value,ConsultancyHours_"+i+".value)\" /><label for='Invoicable'> Invoicable</label></span><br /></span>").appendTo('dd'); 
i++; 
}); 
}); 
</script> 
<script type="text/javascript"> 
//register('Invoicable_"+i+"',RegistrationType_"+i+".value,this.value); 
function invotable(getid,getvalue){ 
var getinvoicetbl = 'invoice_cons'; 
var previnvoice = document.getElementById(getinvoicetbl).innerHTML; 
var dgetid = getid.split("_"); 
var getcount = document.getElementById("consinvoice").value; 
//alert(getcount); 
totalterm =0; 
for (j=8;j<=getcount;j++) 
{ 
totalterm += parseInt(document.getElementById("ConsultancyHours_"+j).value); 
//register('Invoicable_'+j,document.getElementById("RegistrationType_"+j).value,document.getElementById("ConsultancyHours_"+j).value); 
} 
document.getElementById(getinvoicetbl).innerHTML = totalterm; 

} 


function register(getvoice,gettype,getvalue){ 
//alert(getvoice); 
var checkbox = document.getElementById(getvoice).checked; 
var getinvoice = 'invoice_cons'; 
var getnovoice = 'ninvoice_cons'; 
switch (gettype) 
{ 
case "CH": 
     if(checkbox ==true){ 
     //alert("true"); 
     document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue); 
     document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML; 


     document.getElementById(getnovoice).innerHTML = document.getElementById("totinvoice").value - getvalue; 
     alert(document.getElementById("totinvoice").value); 
     alert(document.getElementById(getnovoice).innerHTML); 
     } else { 
       alert(document.getElementById("totinvoice").value); 

     document.getElementById(getnovoice).innerHTML = parseInt(getvalue); 


     document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML; 
     document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue; 
     } 
break; 
case "LH": 
     if(checkbox ==true){ 
     //alert("true"); 
     document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue); 
     document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML; 


     document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue; 

     } else { 
     document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue); 


     document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML; 
     document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue; 
     } 
default: 
     if(checkbox ==true){ 
     //alert("true"); 
     document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue); 
     document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML; 


     document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue; 

     } else { 
     document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue); 


     document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML; 
     document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue; 
     } 
} 
} 
</script> 
<input type="hidden" name="consinvoice" id="consinvoice" value="8" /> 
<input type="hidden" name="totinvoice" id="totinvoice" value="0" /> 
<input type="hidden" name="fromtinvoice" id="fromtinvoice" value="0" /> 
<td width="220"> 
<span id="insert_table"> 
<table class="" id="invtable" width="150" border="1"> 
<tr> 
    <td align="right"> 
    </td> 
    <td align="right" style="padding-left:15px; padding-bottom:10px;"> 
     Invoicable 
    </td> 
    <td align="right" style="padding-left:15px; padding-bottom:10px;"> 
     Non-Invoicable 
    </td> 
    <td align="right" style="padding-left:15px; padding-bottom:10px;"> 
     Total 
    </td> 
</tr> 
<tr> 
    <td style="padding-bottom:10px;">Consultancy</td> 
    <td align="right" id="invoice_cons">-</td> 
    <td align="right" id="ninvoice_cons">-</td> 
    <td align="right" >-</td> 
</tr> 
<tr> 
    <td style="padding-bottom:10px;">Transportation</td> 
    <td align="right" id="invoice_trans">-</td> 
    <td align="right" id="ninvoice_trans">-</td> 
    <td align="right" >-</td> 
</tr> 
<tr> 
    <td style="padding-bottom:10px;">Lunch</td> 
    <td align="right" id="invoice_lun">-</td> 
    <td align="right" id="ninvoice_lun">-</td> 
    <td align="right" >-</td> 
</tr> 
<tr> 
    <td style="padding-bottom:10px;">Total</td> 
    <td align="right" id="invoice_tot">-</td> 
    <td align="right" id="ninvoice_tot">-</td> 
    <td align="right" >-</td> 
</tr> 
<tr> 
</table> 
</span> 
</table> 
<p> 
<label for="RegistrationType"> 
    Type 
</label> 
<span style="margin-left:92px;"> 
:&nbsp;<select name="RegistrationType_8" id="RegistrationType_8" onchange="register('Invoicable_8',this.value,ConsultancyHours_8.value)"> 
<option value="CH">Consultancy Hours</option> 
<option value="LH">Lunch Hours</option> 
<option value="TH">Transportation Hours</option> 
<option value="OH">Other Hours</option> 
</select> 
<input name="ConsultancyHours_8" type="text" id="ConsultancyHours_8" size="5" onkeyup="invotable(this.id,this.value); " /> 
<label for="Hourprice"> 
    Std. Hourprice 
</label> 
<input name="Hourprice_8" type="text" id="Hourprice_8" size="5" /> 
<label for="Hourprice"> 
    - Discount Hourprice 
</label> 
<input name="Hourprice2_8" type="text" id="Hourprice2_8" size="5" /> 
<input name="Invoicable_8" type="checkbox" id="Invoicable_8" onclick="register('Invoicable_8',RegistrationType_8.value,ConsultancyHours_8.value)" checked="checked" /> 
<label for="Invoicable"> 
    Invoicable 
</label> 
<dd id="insert_row"> 
</dd> 
</span> 
</p> 
<p> 
<span style="margin-left:132px;"> 
<input type="button" id="add" value="Add new registration line" /> 
</span> 
</p> 
<div style="margin-left:324px;"> 
</div> 
<br /> 
<p> 
<span style="margin-left:132px;"> 
<input type="submit" name="Submit" id="Submit" value="Save registration" /> 
</span> 
</p> 
+1

Imagen hermosa. Por favor, publique el código también :) –

+3

+1 para el esfuerzo artístico en pseudo-código! – Clive

+0

¿Utiliza alguna biblioteca para JavaScript? – pimvdb

Respuesta

0

ya que parece que está utilizando el Jquery Framework puede utilizar el template feature que permitirá utilizar sus datos de javascript y crear HTML a partir de ella, personalmente no lo he usado. Pero ya que también etiquetó esto con PHP. ¿Por qué no solo hacerlo en PHP?

Por ejemplo:

$formData[]; 
foreach($_POST AS $field => $value) { 
    $formData[$field] = $value; 
} 

Entonces todos los datos están en una matriz y mucho más fácil trabajar con ellos. Solo asegúrese de poner la etiqueta de formulario y usar el atributo method=“post”.

1

Puede crear una función para agregar nueva fila dinámicamente y otra función para calcular la hora escaneando el formulario, luego cuando la ventana está cargada, llame a la función agregar fila para comenzar. No es el código fuente que he creado:

<!DOCTYPE html> 
<style> 
body{margin:0} 
body,th,td{font:16px Arial, Helvetica, sans-serif} 
table{border-spacing:0;border-collapse:collapse;table-layout:fixed} 
th,td{white-space:nowrap;overflow:hidden} 
th{font-weight:700} 
#invtable{width:500px;margin:10px auto;border:1px solid #000} 
#invtable th, #invtable td{border:1px solid #000} 
#registrationForm{width:100%} 
#registrationForm td{text-align:center} 
#registrationForm input[type="number"]{width:140px} 
</style> 
<table id="invtable" width="150"> 
<tr> 
<th>Type</th> 
<th>Invoicable</th> 
<th>Non-Invoicable</th> 
<th>Total</th> 
</tr> 
<tr id="consultancy"> 
<th>Consultancy</th> 
<td>0</td> 
<td>0</td> 
<td>0</td> 
</tr> 
<tr id="transportation"> 
<th>Transportation</th> 
<td>0</td> 
<td>0</td> 
<td>0</td> 
</tr> 
<tr id="lunch"> 
<th>Lunch</th> 
<td>0</td> 
<td>0</td> 
<td>0</td> 
</tr> 
<tr id="other"> 
<th>Other</th> 
<td>0</td> 
<td>0</td> 
<td>0</td> 
</tr> 
<tr id="total"> 
<th>Total</th> 
<td>0</td> 
<td>0</td> 
<td>0</td> 
</tr> 
</table> 
<table id="registrationForm"></table> 
<p><input type="button" id="addNewRegistrationLine" value="Add new registration line"></p> 
<p><input type="submit" id="saveRegistration" value="Save registration"></p> 
<script> 
var doc = document; 
function calculateHour() { 
    var registrationForm = doc.getElementById('registrationForm'); 
    var registrationFormRows = registrationForm.rows 
    var typeValue = {'CH' : [0,0], 'LH' : [0,0], 'TH' : [0,0], 'OH' : [0,0]}; 
    for (var i = 0, registrationFormRowsLength = registrationFormRows.length, typeSelect, inputs, hourInput, isInvoicable; i < registrationFormRowsLength; ++i) { 
    typeSelect = registrationFormRows[i].getElementsByTagName('SELECT')[0]; 
    inputs = registrationFormRows[i].getElementsByTagName('INPUT'); 
    hourInput = inputs[0]; 
    isInvoicable = inputs[inputs.length - 1].checked ? 0 : 1; 
    typeValue[typeSelect.value][isInvoicable] += hourInput.value - 0; 
    } 

    var total = [0, 0] 

    var consultancyCells = doc.getElementById('consultancy').cells; 
    consultancyCells[1].innerHTML = typeValue['CH'][0]; 
    total[0] += typeValue['CH'][0]; 
    consultancyCells[2].innerHTML = typeValue['CH'][1]; 
    total[1] += typeValue['CH'][1]; 
    consultancyCells[3].innerHTML = typeValue['CH'][0] + typeValue['CH'][1]; 

    var transportationCells = doc.getElementById('transportation').cells; 
    transportationCells[1].innerHTML = typeValue['TH'][0]; 
    total[0] += typeValue['TH'][0]; 
    transportationCells[2].innerHTML = typeValue['TH'][1]; 
    total[1] += typeValue['TH'][1]; 
    transportationCells[3].innerHTML = typeValue['TH'][0] + typeValue['TH'][1]; 

    var lunchCells = doc.getElementById('lunch').cells; 
    lunchCells[1].innerHTML = typeValue['LH'][0]; 
    total[0] += typeValue['LH'][0]; 
    lunchCells[2].innerHTML = typeValue['LH'][1]; 
    total[1] += typeValue['LH'][1]; 
    lunchCells[3].innerHTML = typeValue['LH'][0] + typeValue['LH'][1]; 

    var otherCells = doc.getElementById('other').cells; 
    otherCells[1].innerHTML = typeValue['OH'][0]; 
    total[0] += typeValue['OH'][0]; 
    otherCells[2].innerHTML = typeValue['OH'][1]; 
    total[1] += typeValue['OH'][1]; 
    otherCells[3].innerHTML = typeValue['OH'][0] + typeValue['OH'][1]; 

    var totalCells = doc.getElementById('total').cells; 
    totalCells[1].innerHTML = total[0]; 
    totalCells[2].innerHTML = total[1]; 
    totalCells[3].innerHTML = total[0] + total[1]; 
} 

function addNewRegistrationLine() { 
    var registrationForm = doc.getElementById('registrationForm'); 
    var row = registrationForm.insertRow(registrationForm.rows.length); 
    var typeSelectCell = row.insertCell(0); 
    var type = [['CH', 'Consultancy Hours'], ['LH', 'Lunch Hours'], ['TH', 'Transportation Hours'], ['OH', 'Other Hours']]; 
    var typeSelect = doc.createElement('SELECT'); 
    for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) { 
    option = doc.createElement('OPTION'); 
    option.value = type[i][0]; 
    option.innerHTML = type[i][1]; 
    typeSelect.appendChild(option); 
    } 
    typeSelect.onchange = calculateHour; 
    var typeLabel = doc.createElement('LABEL'); 
    typeLabel.innerHTML = 'Type'; 
    typeLabel.appendChild(typeSelect); 
    typeSelectCell.appendChild(typeLabel); 
    var hourInput = doc.createElement('INPUT'); 
    hourInput.type = 'number'; 
    hourInput.onkeyup = calculateHour; 
    typeSelectCell.appendChild(hourInput); 
    var hourPriceInputCell = row.insertCell(1); 
    var hourPriceInput = doc.createElement('INPUT'); 
    hourPriceInput.type = 'number'; 
    var hourPriceLabel = doc.createElement('LABEL'); 
    hourPriceLabel.innerHTML = 'Std. Hourprice'; 
    hourPriceLabel.appendChild(hourPriceInput); 
    hourPriceInputCell.appendChild(hourPriceLabel); 
    var discountInputCell = row.insertCell(2); 
    var discountInput = doc.createElement('INPUT'); 
    discountInput.type = 'number'; 
    var discountLabel = doc.createElement('LABEL'); 
    discountLabel.innerHTML = '- Discount Hourprice'; 
    discountLabel.appendChild(discountInput); 
    discountInputCell.appendChild(discountLabel); 
    var invoicableCheckBoxCell = row.insertCell(3); 
    var invoicableCheckBox = doc.createElement('INPUT'); 
    invoicableCheckBox.type = 'checkbox'; 
    invoicableCheckBox.onclick = calculateHour; 
    var invoicableLabel = doc.createElement('LABEL'); 
    invoicableLabel.appendChild(invoicableCheckBox); 
    invoicableLabel.appendChild(document.createTextNode('Invoicable'); 
    invoicableCheckBoxCell.appendChild(invoicableLabel); 
} 
doc.getElementById('addNewRegistrationLine').onclick = addNewRegistrationLine; 
window.onload = function() { 
    addNewRegistrationLine(); 
}; 
</script> 

Live example

Cuestiones relacionadas