jQuery undefined value of an existing html element - javascript

I have a jQuery code to check whether a html element with particular id exists or not. I have written the if and else clause of existing and non existing html element. But when the element exists why jQuery returns the value as undefined ?
You can see the jQuery code below. The variable start_time is defined, because it enters the clause condition but the value is detected as undefined. What is wrong with the code?
var count = 0;
for(i=1; i<=n_day; i++){
count = count + 1 ;
var start_time = jQuery("#txtStartTime_detail"+i);
var end_time = jQuery("#txtEndTime_detail"+i);
var start_location = jQuery("#txtStartLocation_detail"+i);
var end_location = jQuery("#txtEndLocation_detail"+i);
var start_location_coor = jQuery('#txtStartLocation_Coordinates_detail'+i);
var end_location_coor = jQuery('#txtEndLocation_Coordinates_detail'+i);
//var day = jQuery('#txtDay'+i);
if(typeof start_time == 'undefined'){
start_time = '';
}else{
start_time = jQuery("#txtStartTime_detail"+i).val();
alert(start_time);
}
if(typeof end_time == 'undefined'){
end_time = '';
}else{
end_time = jQuery("#txtEndTime_detail"+i).val();
}
if(typeof start_location == 'undefined'){
start_location = '';
}else{
start_location = jQuery("#txtStartLocation_detail"+i).val();
}
if(typeof end_location == 'undefined'){
end_location = '';
}else{
end_location = jQuery("#txtEndLocation_detail"+i).val();
}
if(typeof start_location_coor == 'undefined'){
start_location_coor = '';
}else{
start_location_coor = jQuery('#txtStartLocation_Coordinates_detail'+i).val();
}
if(typeof end_location_coor == 'undefined'){
end_location_coor = '';
}else{
end_location_coor = jQuery('#txtEndLocation_Coordinates_detail'+i).val();
}
requestdetail += '<div class="yellow" id="txtDay'+count+'">Day - '+count+' : '+travel_date+'</div>'
+'<div class="table-responsive table-condensed">'
+'<table class="table borderless">'
+'<tbody>'
+'<tr>'
+'<td class="col-left">Travel time</td>'
+'<td class="col-middle"><input type="text" name="txtStartTime_detail[]" id="txtStartTime_detail"'+count+'" class="timepicker" value="'+start_time+'"/></td>'
+'<td class="col-middle"><input type="text" name="txtEndTime_detail[]" id="txtEndTime_detail'+count+'" class="timepicker" value="'+end_time+'" /></td>'
+'<td class="col-right"><div class="error" id="error_time'+count+'"> </div></td>'
+'</tr>'
+'<tr>'
+'<td class="col-left">Location</td>'
+'<td class="col-middle-2"><input type="text" size="100" name="txtStartLocation_detail[]" id="txtStartLocation_detail'+count+'" class="inputWithImge" value="'+start_location+'" onmouseover="display_text(this)" />'
+ '<img src="'+base_url+'" class="location-icon" alt="Click to search the location" name="location-icon" value="StartLocation_detail'+count+'" title="Click to show map"/>'
+ '</td>'
+'<td class="col-middle-2"><input type="text" name="txtEndLocation_detail[]" id="txtEndLocation_detail'+count+'" class="inputWithImge" value="'+end_location+'" onmouseover="display_text(this)"/>'
+ '<img src="'+base_url+'" class="location-icon" alt="Click to search the location" name="location-icon" value="EndLocation_detail'+count+'" title="Click to show map"/>'
+ '</td>'
+'<td class="col-right"><div class="error" id="error_location'+count+'"> </div></td>'
+'</tr>'
+'</tbody>'
+'<input type="hidden" name="txtStartLocation_Coordinates_detail[]" id="txtStartLocation_Coordinates_detail'+count+'" value="'+start_location_coor+'">'
+'<input type="hidden" name="txtEndLocation_Coordinates_detail[]" id="txtEndLocation_Coordinates_detail'+count+'" value="'+end_location_coor+'">'
+'</table>'
+'</div>';
travel_date = new Date(jQuery("#txtStartDate").val());
travel_date.setDate(startDate.getDate() + i);
travel_date = jQuery.datepicker.formatDate("DD, MM d, yy", new Date(travel_date));
}
the html elements are populated dynamically in codeigniter and returns to browsers as a html String.
here is how I display the html string :
<form name="frm_RRequest" action="#" method="post">
<?php
if(strlen($current_request)>0 || $current_request!=null){
echo $current_request;
echo '<div><input type="button" name="btn_Update" class="button" value="Update" /></div>';
}else{
$site_url = site_url("user/recommendation_request");
echo '<div class="yellow">you have no current request, you can make a new request here >> Recommendation Request</div>';
}
?>
</form>
and here is how the elements are created in codeigniter
'<div class="yellow" id="txtDay'.$count.'">Day - '.$count.' : '.$travel_date.'</div>'
.'<div class="table-responsive table-condensed">'
.'<table class="table borderless">'
.'<tbody>'
.'<tr>'
.'<td class="col-left">Travel time</td>'
.'<td class="col-middle"><input type="text" name="txtStartTime_detail[]" id="txtStartTime_detail"'.$count.'" class="timepicker" value="'.$start_time.'"/></td>'
.'<td class="col-middle"><input type="text" name="txtEndTime_detail[]" id="txtEndTime_detail'.$count.'" class="timepicker" value="'.$end_time.'" /></td>'
.'<td class="col-right"><div class="error" id="error_time'.$count.'"> </div></td>'
.'</tr>'
.'<tr>'
.'<td class="col-left">Location</td>'
.'<td class="col-middle-2"><input type="text" size="100" name="txtStartLocation_detail[]" id="txtStartLocation_detail'.$count.'" class="inputWithImge" value="'.$row->start_location.'" onmouseover="display_text(this)" />'
. '<img src="'.$base_url.'" class="location-icon" alt="Click to search the location" name="location-icon" value="StartLocation_detail'.$count.'" title="Click to show map"/>'
. '</td>'
.'<td class="col-middle-2"><input type="text" name="txtEndLocation_detail[]" id="txtEndLocation_detail'.$count.'" class="inputWithImge" value="'.$row->end_location.'" onmouseover="display_text(this)"/>'
. '<img src="'.$base_url.'" class="location-icon" alt="Click to search the location" name="location-icon" value="EndLocation_detail'.$count.'" title="Click to show map"/>'
. '</td>'
.'<td class="col-right"><div class="error" id="error_location'.$count.'"> </div></td>'
.'</tr>'
.'</tbody>'
.'<input type="hidden" name="txtStartLocation_Coordinates_detail[]" id="txtStartLocation_Coordinates_detail'.$count.'" value="'.$start_location_coor.'">'
.'<input type="hidden" name="txtEndLocation_Coordinates_detail[]" id="txtEndLocation_Coordinates_detail'.$count.'" value="'.$end_location_coor.'">'
.'</table>'
.'</div>';

Your problem is in the strings that you use to create the content.
You have
... id="txtStartTime_detail"'+count+'".....
which will create the ID
...id = "txtStartTime_detail"1"...
You just have to remove the extra double quotes "'+count"' should be '+count+'"

Related

Is there a way to loop inside a variable which contains html

I'm trying to set a select button which gets the options from an ajax call.
The ajax call is working. The problem is when I try to create the variable which contains the html. I don't know the way to iterate and create multiple option inside the variable.
This is the ajax call:
$.ajax({
url: '/facturas/data',
type: 'GET',
success: function(s) {
var currency = s.currency;
var rendiciones = s.rendiciones;
var tipo_comprobante = s.tipo_comprobante;
var tipo_gasto = s.tipo_gasto;
var fm_table_row = '<td>'+
'<div class="inputfield"><select name="fm_tipo_comp_select"><option value="" disabled="" selected="">Comprobante</option>'+
tipo_comprobante.forEach(row){
'<option value="id">nombre</option>'+
}
'</select><label>Tipo comprobante</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_tipo_gasto"><option value="" disabled="" selected="">Tipo gasto</option>'+
'<option value="id">nombre </option>'+
'</select><label>Tipo gasto</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_serie" type="text" name="fm_serie" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_ndoc" type="text" name="fm_ndoc" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_ruc" type="text" name="fm_ruc" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_rs" type="text" name="fm_rs" disabled="disabled" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="datepicker validate" id="fm_fecha" type="text" name="fm_fecha" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_moneda"><option value="" disabled="" selected="">Moneda</option>'+
'<option value="id">nombre </option>'+
'</select><label>Moneda</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate" id="fm_monto" type="number" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_retencion"><option value="" disabled="" selected="">RetenciĆ³n</option>'+
'<option value="id">nombre </option>'+
'</select><label>RetenciĆ³n</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><a class="btn-floating btn-small waves-effect waves-light red delete-btn"><i class="material-icons">delete</i></a></div>'+
'</td>';
}
});
I added the tipo_comprobante.forEach(row){} to show what I want to do.
With reduce and ES6 String templates
var options = ['cat', 'dog', 'fish'].reduce((acc, value) =>
acc + `<option value="${value}">${value}</option>`, '');
var result = `<select>${options}</select>`;
Inside the ajax call, you can create a string variable and use whatever loop (for loop) you like to set it, and then use the variable inside the ajax call in the desired location within the html.
var myOptionsValues = ['cat', 'dog', 'fish'];
var myOptionsHtml = '';
myOptions.forEach(function (optionValue) {
myOptionsHtml+='<option value="' + optionValue + '">' + optionValue + '</option>';
});
var myHtmlForAjax = '<select>' + myOptions + '</select>';
Yes. Just add it to a DOM element, then use .children to get it in Array form:
/* a string with HTML text */
const someString = `
<p>Paragraph1</p>
<p>Paragraph2</p>
<p>Paragraph3</p>
`;
/* create a temporary element */
const temp = document.createElement("div");
/* add the HTML text to that element */
temp.innerHTML = someString;
/* create the array */
const array = Array.from(temp.children);
/* loop */
for(let i = 0; i < array.length; i++){
const p = array[i];
alert(p); // or do whatever
}

JavaScript Function not taking the array index returning as undefined

I have created a Crud application and have a data() which accepts Json
user = {name: name, age: age, email: email, dob: do}
as input.
When I call the editUser(), the array index is not being taken.
but when I pass the array index statically through the console, the function works as it should.
How should I correct the mistake?
I also have an updateUser() which also faces the same problem.
function read(users) {
var html = "<table border='1|1' class=\"table container\">";
var userhtml = document.getElementById('user');
userhtml.innerHTML = '';
var t = Object.keys(users[0]);
for (var i = 0; i <= 0; i++) {
html += "<tr>";
html += "<th>" + t[0] + "</th>";
html += "<th>" + t[1] + "</th>";
html += "<th>" + t[2] + "</th>";
html += "<th>" + t[3] + "</th>";
html += "<th>" + " Edit" + "</th>";
html += "<th>" + "Delete" + " </th>";
html += "</tr>"
for (var j = i; j < users.length; j++) {
html += "<tr>";
html += "<td>" + users[j].name + "</td>";
html += "<td>" + users[j].age + "</td>";
html += "<td>" + users[j].email + "</td>";
html += "<td>" + users[j].dob + "</td>";
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
html += "<td>" + "<a href='#' onclick='deleteUsers()'>Delete</a>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("user").innerHTML = html;
}
}
function editUser(index) {
debugger;
var userhtml1 = document.getElementById('edit');
userhtml1.innerHTML = '';
for (var i = 0; i < users.length; i++) {
if (i == index) {
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser()">Update</button>';
} else {
userhtml1.innerHTML += '';
}
}
}
function updateUser(index) {
debugger;
var updatename = document.getElementById('EditName').value;
var updateage = document.getElementById('EditAge').value;
var updateemail = document.getElementById('EditEmail').value;
var updatedob = document.getElementById('EditDOB').value;
if (updatename == '' || updateemail == '' || updateage == '' || updatedob == '') {
alert("Please Fill the Fields!");
}
else {
users[index].name = updatename;
users[index].email = updateemail;
users[index].age = updateage;
users[index].dob = updatedob;
read(users);
}
}
<form action="#" onsubmit="data(name, age, email, dob)">
<!--data(name, age, email, dob)-->
<!--onsubmit="return validate()"-->
<div class="form-group">
<label class="form-text">Name :</label>
<input type="text" id="Name" placeholder="Enter Name" class="form-control" " />
<span id="ErrorName " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Age :</label>
<input type="text " id="Age " placeholder="Enter Age " class="form-control " />
<span id="ErrorAge " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Email :</label>
<input type="text " id="Email " placeholder="Enter Email " class="form-control " />
<span id="ErrorEmail " class="text-danger " />
</div>
<div class="form-group ">
<label class="form-text ">Password :</label>
<input type="password " id="Password " placeholder="Enter Password " class="form-control " />
<span id="ErrorPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Confirm Password :</label>
<input type="password " id="ConfirmPassword " placeholder="Confirm Password " class="form-control " onblur=" " />
<span id="ErrorConfirmPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Date of Birth :</label>
<input type="date " id="DOB " class="form-control " />
<span id="ErrorDOB " class="text-danger "></span>
</div>
<div class="form-group col-lg-12 text-center ">
<input type="submit " id="Submit " class="btn btn-success " />
</div>
</form>
<div class="container " id="user ">
</div>
<br />
<div class="form-group " id="edit ">
</div>
You just forgot to pass the argument. Try this please:
// Change this line
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
// For this one
html += "<td>" + "<a href='#' onclick='editUser("+j+")'>Edit</a>" + "</td>";
Also, note that your for statement only executes once.. you can just remove it leaving the code inside untouched.
// This executes only once, no matter what.
for (var i = 0; i <= 0; i++) { // <-- remove this
// your code..
} // <-- remove this
// Because it would be the same as just doing:
// your code..
Edit for the updateUser problem:
// For the updateUser problem, note that I added the i variable for the call:
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser('+i+')">Update</button>';

Calculate total of all dynamic items upon submit of form including copied items

I am trying to calculate the total of a list of dynamic form option items, example :
product name
product description
quantity
price
total
I have a script that automatically adds item rows :
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type="text" data-type="productCode" name="data[Invoice][itemNo][]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="data[Invoice][itemName][]" id="itemName_'+i+'" class="form-control" autocomplete="off"></td>';
html += '<td><input type="text" name="data[Invoice][price][]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][quantity][]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][total][]" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input class="case" type="checkbox" name="data[Invoice][staged][]" id="itemStaged_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
and the script that does the totalling :
$(document).on('change keyup blur','#tax',function(){
calculateTotal();
});
//total price calculation
function calculateTotal(){
subTotal = 0 ; total = 0;
$('.totalLinePrice').each(function(){
if($(this).val() != '' )subTotal += parseFloat( $(this).val() );
});
$('#subTotal').val( subTotal.toFixed(2) );
tax = $('#tax').val();
if(tax != '' && typeof(tax) != "undefined" ){
taxAmount = subTotal * ( parseFloat(tax) /100 );
$('#taxAmount').val(taxAmount.toFixed(2));
total = subTotal + taxAmount;
}else{
$('#taxAmount').val(0);
total = subTotal;
}
$('#totalAftertax').val( total.toFixed(2) );
calculateAmountDue();
}
So what happens now, you tab or press enter to cycle through the fields, and after you update the qty and tab through, it updates the total for that item, as well as the overall total.
The PROBLEM is that if you COPY and PASTE form fields using the following script :
//copies the selected table rows to new ones
$(".copy").on('click', function() {
var origs=$('.case:checkbox:checked');
for(var a=0; a<origs.length; a++) {
addNewRow();
var arr = origs.closest('tr')[a].id.split('_');
var id = arr[arr.length-1];
var dat = getValues(id);
setValues(i-1, dat);
}
$('#check_all').add(origs).prop("checked", false);
// Tried adding calculateTotal(); in this line to no avail...
});
The copied rows are not updated on the overall total. This is driving me insane, does anyone have a solution or tutorial on how to do this?
Requests : (show addNewRow function)
var addNewRow = function(id){
html = '<tr id="tr_'+i+'">';
html += '<input type="hidden" id="stock_'+i+'"/>';
html += '<input type="hidden" id="stockMaintainer_'+i+'" name="data[InvoiceDetail]['+i+'][stockMaintainer]" />';
html += '<input type="hidden" id="previousQuantity_'+i+'"/>';
html += '<input type="hidden" id="invoiceDetailId_'+i+'"/>';
html += '<td><input class="case" id="caseNo_'+i+'" type="checkbox" onkeyup="return tabE(this,event);"/></td>';
html += '<td class="prod_c"><input type="text" data-type="productCode" name="data[InvoiceDetail]['+i+'][product_id]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off" onkeyup="return tabE(this,event);">';
html +='<span class="add_icon" id="add_icon_'+i+'"> <i class="fa fa-plus-circle"></i></span>';
html +='<span class="subtract_icon" id="subtract_icon_'+i+'"><i class="fa fa-minus-circle"></i></span>';
html +='</td>';
html += '<td><input type="text" data-type="productName" name="data[InvoiceDetail]['+i+'][productName]" id="itemName_'+i+'" class="form-control" autocomplete="off" onkeyup="return tabE(this,event);"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][price]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][quantity]" id="quantity_'+i+'" class="form-control changesNo quanyityChange" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;">';
html += '</td>';
html += '<td><input type="text" id="total_'+i+'" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail]['+i+'][staged]" id="staged_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail]['+i+'][added]" id="added_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select name="data[InvoiceDetail]['+i+'][location]" id="location_1'+i+'" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
html += '</tr>';
if( typeof id !== "undefined"){
$('#tr_'+id).after(html);
}else{
$('table').append(html);
}
$('#caseNo_'+i).focus();
i++;
}
(getValues) Code :
var getValues=function(id){
var inputs=$('#tr_'+id).find('select,input,textarea').filter('[name]');
var values={};
for(var i=0; i<inputs.length;i++){
var cur=inputs[i];
values[cur.name.match(/\[\w+]$/)||cur.name] = $(cur).is(':checkbox, :radio') ? cur.checked : cur.value;
}
return values;
};
(setValues) :
var setValues=function(id,values){
var inputs=$('#tr_'+id);
for(var i in values){
var cur=inputs.find('[name$="'+i+'"]');
if(cur.is(':checkbox, :radio')) {
cur.prop('checked', values[i]);
} else {
cur.val(values[i]);
}
}
};
The addNewRow function is not setting a name attribute on the total textbox.
However, your getValues and setValues functions are using the [name] attribute selector to get and set values in the cloned rows. Because addNewRow did not set the name attribute, the total value fails to populate in the cloned row, and therefore the total does not change because calculateTotal interprets this value as 0.
Problem code is here:
html += '<td><input type="text" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
Here is the fixed line of code: (and also remember to call calculateTotal in your copy handler)
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][total]" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
See working (but slightly simplified) snippet below: (or see the fiddle)
$(document).on('change keyup blur', '#tax', function() {
calculateTotal();
});
IsNumeric = tabE = function() {
return true
}
var i = 0;
var addNewRow = function(id) {
var html = '<tr id="tr_' + i + '">';
html += '<input type="hidden" id="stock_' + i + '"/>';
html += '<input type="hidden" id="stockMaintainer_' + i + '" name="data[InvoiceDetail][' + i + '][stockMaintainer]" />';
html += '<input type="hidden" id="previousQuantity_' + i + '"/>';
html += '<input type="hidden" id="invoiceDetailId_' + i + '"/>';
html += '<td><input class="case" id="caseNo_' + i + '" type="checkbox" onkeyup="return tabE(this,event);"/></td>';
html += '<td class="prod_c"><input type="text" data-type="productCode" name="data[InvoiceDetail][' + i + '][product_id]" id="itemNo_' + i + '" class="form-control autocomplete_txt" autocomplete="off" onkeyup="return tabE(this,event);">';
html += '<span class="add_icon" id="add_icon_' + i + '"> <i class="fa fa-plus-circle"></i></span>';
html += '<span class="subtract_icon" id="subtract_icon_' + i + '"><i class="fa fa-minus-circle"></i></span>';
html += '</td>';
html += '<td><input type="text" data-type="productName" name="data[InvoiceDetail][' + i + '][productName]" id="itemName_' + i + '" class="form-control" autocomplete="off" onkeyup="return tabE(this,event);"></td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][price]" id="price_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][quantity]" id="quantity_' + i + '" class="form-control changesNo quanyityChange" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;">';
html += '</td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][total]" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail][' + i + '][staged]" id="staged_1' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail][' + i + '][added]" id="added_1' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select name="data[InvoiceDetail][' + i + '][location]" id="location_1' + i + '" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
html += '</tr>';
if (typeof id !== "undefined") {
$('#tr_' + id).after(html);
} else {
$('table').append(html);
}
$('#caseNo_' + i).focus();
i++;
}
$(".addmore").on('click', function() {
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type="text" data-type="productCode" name="data[Invoice][itemNo][]" id="itemNo_' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="data[Invoice][itemName][]" id="itemName_' + i + '" class="form-control" autocomplete="off"></td>';
html += '<td><input type="text" name="data[Invoice][price][]" id="price_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][quantity][]" id="quantity_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][total][]" id="total_' + i + '" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input class="case" type="checkbox" name="data[Invoice][staged][]" id="itemStaged_' + i + '"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
//copies the selected table rows to new ones
$(".copy").on('click', function() {
var origs = $('.case:checkbox:checked');
for (var a = 0; a < origs.length; a++) {
addNewRow();
var arr = origs.closest('tr')[a].id.split('_');
var id = arr[arr.length - 1];
var dat = getValues(id);
setValues(i - 1, dat);
}
$('#check_all').add(origs).prop("checked", false);
calculateTotal();
});
//total price calculation
function calculateTotal() {
subTotal = 0;
total = 0;
$('.totalLinePrice').each(function() {
if ($(this).val() != '') subTotal += parseFloat($(this).val());
});
$('#subTotal').val(subTotal.toFixed(2));
tax = $('#tax').val();
if (tax != '' && typeof(tax) != "undefined") {
taxAmount = subTotal * (parseFloat(tax) / 100);
$('#taxAmount').val(taxAmount.toFixed(2));
total = subTotal + taxAmount;
} else {
$('#taxAmount').val(0);
total = subTotal;
}
$('#totalAftertax').val(total.toFixed(2));
//calculateAmountDue();
}
var getValues = function(id) {
var inputs = $('#tr_' + id).find('select,input,textarea').filter('[name]');
var values = {};
for (var i = 0; i < inputs.length; i++) {
var cur = inputs[i];
values[cur.name.match(/\[\w+]$/) || cur.name] = $(cur).is(':checkbox, :radio') ? cur.checked : cur.value;
}
return values;
};
var setValues = function(id, values) {
var inputs = $('#tr_' + id);
for (var i in values) {
var cur = inputs.find('[name$="' + i + '"]');
if (cur.is(':checkbox, :radio')) {
cur.prop('checked', values[i]);
} else {
cur.val(values[i]);
}
}
};
addNewRow()
addNewRow()
input {
width: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Tax rate
<input type="text" id="tax" value="8.7">
</div>
<div>
Tax amt
<input type="text" id="taxAmount" value="0">
</div>
<div>
Total
<input type="text" id="totalAftertax" value="0">
</div>
COPY CHECKED ROWS (check some rows first)
<table>
<thead>
<tr>
<th>copy</th>
<th>product code</th>
<th>product name</th>
<th>price</th>
<th>qty</th>
<th>total</th>
<th>staged</th>
<th>added</th>
<th>location</th>
</tr>
</thead>
</table>
Here you are calling calculateTotal(); function on change keyup and blur
events.this works as long as you interact with form elements.
but when you copy the row.you wont be interacting with textboxes.so those change,blur and keyup events wont get fired and as a result calculateTotal()
will not be executed.as a result you cant see any update on total value.
to overcome this you have to call calculateTotal() in copy function.

Symfony Redirect for some action

I use this dashboard and when I pushed button "Add New" create dynamics button save, I find this button in js file this dasboard:
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '">';
jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '">';
jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[2] + '">';
jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '">';
jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[4] + '">';
jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[5] + '">';
jqTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[6] + '">';
jqTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[7] + '">';
jqTds[8].innerHTML = '<a class="edit" href="??????????">Save</a>';
jqTds[9].innerHTML = '<a class="cancel" href="?????????">Cancel</a>';
}
and my question
I have routing for add new developer how I put my routing this "href=" or maybe redirect for my creatAction ????
If you want use that way,
put hidden input and then get value via jQuery
HTML
<input type="hidden" id="form-url" val="{{ path('my_route') }}">
in edit row fundtion
jqTds[9].innerHTML = '<a class="cancel" href="'+$('#form-url').val();+'">Cancel</a>';

Sum values Javascript

Here http://webmark.pt/sharepics/orders.png is the sales order layout (./sharepics/add.zip the full code) that I need to customize.
Problem:
Dynamically sum the cells between size 39 and 50, and put the value in the Pairs (quantity).
Already managed to add the lines, but the result is added to the lines immediately below.
The code that does this operation:
var newTr = $('<tr id="row_' + count + '"></tr>');
newTr.html('<td><input name="product' + count + '" type="hidden" value="' + item_code + '"><input class="span5 tran" name="item' + count + '" type="text" value="' + item_code + '"></td>
.......
<td><input class="input-block-level text-center" name="sort' + count + '" type="text" value="" id="sort-' + count + '" onClick="this.select();"></td>
<td><input class="input-block-level text-center" name="size39' + count + '" type="text" value="" id="size39-' + count + '" onClick="this.select();"></td>
......
<td><input class="input-block-level text-center" name="size50' + count + '" type="text" value="" id="size50-' + count + '" onClick="this.select();"></td>
<td><input class="input-block-level text-center" name="quantity' + count + '" type="text" value="1" id="quantity-' + count + '" onClick="this.select();"></td>
<td><input class="span2 tran" style="text-align:right;" name="unit_price' + count + '" type="text" id="price-' + count + '" value="' + item_price + '"></td>
<?php echo '<td><input class="span2 tran2" name="cart\'+ count +\'" type="text" value="" required="required" data-error="' . $this->lang->line("cart") . ' ' . $this->lang->line("is_required") . '"></td>';
if (DISCOUNT_OPTION == 2) {
echo '<td><select class="span2 select tran" data-placeholder="Select..." name="discount\' + count + \'" id="discount-\' + count + \'">';
foreach ($discounts as $discount) {
echo "<option value=" . $discount->id;
if ($discount->id == DEFAULT_DISCOUNT) {
echo ' selected="selected"';
}
echo ">" . $discount->name . "</option>";
}
echo '</select></td>';
}
?>
<td><input class="input-block-level text-center" name="subtotalpares' + count + '" type="text" value="" id="subtotalpares" disabled onClick="this.select();"></td>
<td><i class="icon-trash tip del" id="' + count + '" title="Remove this Item" style="cursor:pointer;" data-placement="right"></i></td>');
newTr.prependTo("#dyTable");
count++;
an++;
total += parseFloat(item_price);
$("input[id^=size]").keyup(function () {
var sum = 0;
$("input[id^=size]").each(function () {
sum += (parseInt(this.value) ? parseInt(this.value) : 1);
});
$("input[id^=quantity]").val(sum);
});
I look forward to some help!

Categories