How to clone element when i use $.append - javascript

I have some data from json when page load i pull to my combo box.
function DataProvide(){
//Load data from json
selectValues = {
"pilih" : "-Pilih-",
"id" : "ID",
"emp_name" : "Employee Name",
"photo_path" : "Photo Path",
"emp_id" : "Employee ID",
"birth_place" : "Birth Place",
"birth_date" : "Birth Date"
};
$.each(selectValues, function(key, value) {
$('#data1_1')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
$(document).ready(function() {
DataProvide();
});
When the page is load, I successfully generated the data input into the combo box, but my problem is when I want to perform additional row in the table using $.Append....
$(".addCF").click(function(){
count += 1;
$("#customFields").append(
'<tr>'
+ '<td>'
+ '<select id="data1_'+count+'" class="tabelBaru" name="data1[]">'
+ '<option value="pilih" selected >Pilih</option>'
+ ... clone from element $('#data1_1')
+ ... clone from element $('#data1_1')
+ ... clone from element $('#data1_1')
+ '</select>'
+ '</td>'
+ '<td>'
+ '<input id="data2_'+count+'" type="text" name="data2[]" class="data2" value="" placeholder=""/>'
+ '</td>'
+ '<td>'
+ '<input id="data3_'+count+'" type="email" name="data3[]" class="data3" value="" placeholder=""/>'
+ '</td>'
+ '<td>'
+ 'Remove'
+ '</td>'
+ '</tr>'
);
});
How do I use the function $.clone to take $('#data1_1') element along with all data that was created when the first page is opened??

Try
$(".addCF").click(function () {
count += 1;
var $row = $('<tr>' + '<td>' + '</td>' + '<td>' + '<input id="data2_' + count + '" type="text" name="data2[]" class="data2" value="" placeholder=""/>' + '</td>' + '<td>' + '<input id="data3_' + count + '" type="email" name="data3[]" class="data3" value="" placeholder=""/>' + '</td>' + '<td>' + 'Remove' + '</td>' + '</tr>').appendTo("#customFields");
$row.find('td:first').append($('#data1_1').clone())
});

The following should do the trick:
var myHtml = ""
$.each(selectValues, function(key, value) {
myHtml += "<option value=\"" + key + "\">" + value + "</option>";
});
$("data1_1").append(myHtml);
Note that building it as a string, while it might not look as good is always more efficient.

Related

How to multiply value of column A with Value of column B To get value of column c in javascript

Kindly assist sort this issue,i would like to multiply value to column A let say quantity with value of column B lets say Cost to get value of Column C Total.
With Just parsing one row to the table am able to achieve this but am stuck if Column A quantity which is editable value is changed.i Total does not change.So how can i achieve like maybe after user editing is complete or after enter key press.
$table.append(
'<tr class="dynamic">' +
'<td> <input type = "hidden" class= "txtStockID" name =
"StockID" ' +
'value = "' +id + '" /> ' +id+ '</td>' +
'<td>' +
item +
'</td>' +
'<td id="qty" class= "qty" type="number" contenteditable>' +
qty +
'</td>' +
'<td>' +
retail +
'</td>' +
'<td>' +
cost +
'</td> ' +
'<td>' +
this.cells[5].innerHTML +
'</td>' +
'<td>' +
tax +
'</td>' +
'<td>' +
vat +
'</td>' +
'<td id="total">' +
total +
'</td>' +
'<td><a data-itemId="0" href="#" class="deleteItem btn btn-
danger btn-flat btn-xs ' +
'glyphicon glyphicon-trash"></a>' +
'</td>' +
'</tr>'
);
$(document).on('change, keyup',
$('.qty'),
function () {
var rows = $('.dynamicRows');
$.each(rows,
function (index, item) {
var quantity =
Number($(this).children('td').eq(2).text());
var cost =
Number($(this).children('td').eq(4).text());
var amount = (quantity * cost).toFixed(2);
$(this).children('td').eq(8).val(amount);
});
});
update_total();
}
});
Make sure the second argument of your on() event binder is a string selector (e.g. '.qty'), not a jQuery object => http://api.jquery.com/on/.
$(document).on('keyup', '.qty', function () {
var rows = $('.dynamic');
$.each(rows, function (index, item) {
var quantity =
Number($(this).children('td').eq(2).text());
var cost =
Number($(this).children('td').eq(4).text());
var amount = (quantity * cost).toFixed(2);
$(this).children('td').eq(8).text(amount);
});
update_total();
});

Depend on the popup's table data, parent's table data showing item is different

I have a popup modal like this one.
When I click 'ADD' button, all the data from popup's table is shown at the table of the parent's. Like this one.
The problem is that I don't want to show the plus sign "+", if there is no data in textbox2s.
Here is the code at popup.js
function add_to_prent_table(){
var popupTable = [];
var i = 0;
$('#testing > tbody > tr').each(function () {
popupTable[i] = [
$(this).find("#test_number").val(),
$(this).find("#type_1").val(),
$(this).find("#type_2").val(),
$(this).find("#place_1").val(),
$(this).find("#place_2").val(),
];
i++;
var newRow = '<tr>'+
'<td id ="td_center">'+
$(this).find("#test_piece_number").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#type_1").val() + ' + ' +
$(this).find("#type_2").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#place_1").val() + ' + ' +
$(this).find("#place_2").val() +
'</td>'+
'</tr>';
$('#testing_parent tbody').append(newRow);
});
}
How can I fix this?
It's messy but you can replace the first ' + ' with this:
$(this).find("#type_2").val() ? ' + ' : ''
And replace the second ' + ' with
$(this).find("#place_2").val() ? ' + ' : ''
Basically you're looking to see if #type_2 and #place_2 have values. If they do, add a ' + '. If not, add nothing.
Try this;
function add_to_prent_table() {
var popupTable = [];
var i = 0;
$('#testing > tbody > tr').each(function () {
var testNumber = $(this).find("#test_number").val();
var firstType = $(this).find("#type_1").val();
var secondType = $(this).find("#type_2").val();
var firstPlace = $(this).find("#place_1").val();
var secondPlace = $(this).find("#place_2").val();
popupTable[i] = [
testNumber,
firstType,
secondType,
firstPlace,
secondPlace,
];
i++;
var newRow = '<tr>' +
'<td id ="td_center">' +
$(this).find("#test_piece_number").val() +
'</td>' +
'<td id ="td_center">' +
firstType + secondType ? (' + ' + secondType) : '' +
'</td>' +
'<td id ="td_center">' +
firstPlace + secondPlace ? (' + ' + secondPlace) : '' +
'</td>' +
'</tr>';
$('#testing_parent tbody').append(newRow);
});
}
Simply you can add condition before adding plus sign like below,
var newRow = '<tr>'+
'<td id ="td_center">'+
$(this).find("#test_piece_number").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#type_1").val()
if($(this).find("#type_2").val() != "")
{
' + ' + $(this).find("#type_2").val()
}
'</td>'+
'<td id ="td_center">'+
$(this).find("#place_1").val()
if($(this).find("#place_2").val() != "")
{
' + ' + $(this).find("#place_2").val()
}
'</td>'+
'</tr>';

Can't get value from table td with quotes

Here I am creating dynamic table
function addToMLContainer(id, mlName, mlAddress) {
return '<td><s:text>' + mlName + ' ' + mlAddress + '</s:text></td>' +
'<td hidden="hidden">' + id + '<input name="mlId" type="hidden" value = "' + id + '" /></td>' +
'<td hidden="hidden"><input name="mlFullName" type="hidden" value = "' + mlName + ' ' + mlAddress + '" /></td>' +
'<td align="center"><img src="/delete.png" class="remove" onclick="this.closest(\'tr\').remove()"/></td>'
}
And here I am getting value of tr:
var t = document.getElementById("AddedMlsContainer");
for (var i = 1, row; row = t.rows[i]; i++) {
selectedMerchants = selectedMerchants + " " + row.cells[2].children[0].value + "\n";
}
The problem is I can't get value with double or single quotes like <I'm "blabla">
Finally I did it by removing input field and unnesessary td:
'<td>' + mlName + ' ' + mlAddress + '</td>' +
'<td hidden="hidden">' + id + '<input name="mlId" type="hidden" value = "' + id + '" /></td>' +
'<td align="center"><img src="/delete.png" class="remove" onclick="this.closest(\'tr\').remove()"/></td>'
Then I used innerHtml
var t = document.getElementById("AddedMlsContainer");
for (var i = 1, row; row = t.rows[i]; i++) {
selectedMerchants = selectedMerchants + " " + row.cells[0].innerHTML.replace(/ /g,'') + "\n";
}

Show values from query in a table using php and ajax

I have a problem with my code, So I have an array and I pass to template, the array is like this :
Array
(
[0] => Array
(
[ref_article] => 1903
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 14.00
[gifts_number] => 3
)
[1] => Array
(
[ref_article] => 1907
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 12.00
[gifts_number] => 1
)
)
Now in template I do :
for (var item in result) {
document.getElementById('order_information').setAttribute('class','display-on');
document.getElementById('order_information').setAttribute('class','table');
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>' + 'description' + '</td>'+
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>' + 'disponibilite' +
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").html(html);
console.log(result[item]['ref_article']);
}
The problem is that only the last <td></td> shows on the page, in this case only the article with [ref_article] = 1907. What am I doing wrong? Can you help me please? Thanks in advance
The issue is because you are using html() to add the content - this will overwrite any pre-existing content in the #content-order element. Instead, try using append():
$("#content-order").append(html);
Also note that you can amend your first two lines to use a jQuery selector and the addClass() method:
$('#order_information').addClass('display-on table');
If you want to clear information added from a previous request you can use .empty() before the for loop that appends new content. Here's a full example:
// $.ajax({...
success: function(result) {
$("#content-order").empty(); // remove existing content
$('#order_information').addClass('display-on table');
for (var item in result) {
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").append(html);
console.log(result[item]['ref_article']);
}
}
Try using this code
var html = '<table>';
for (var item in result) {
html += '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>' +
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
console.log(result[item]['ref_article']);
}
html += '</table>';
$("#content-order").html(html);

Errors in js function that builds a table row

I am building a table row in a jQuery $.ajax() call that builds a row on successful execution of a PHP script.
I'm calling a function that builds a new table row based on the script results. Here is the function:
function addNewRow(addDocs, newClassID, classNumberAdd, classNameAdd) {
var newRow = '';
newRow += $('#classesTable tbody:last').after('<tbody>' +
'<tr bgcolor="#EFE5D3" style="font-weight: bold;">' +
'<td width="35px"><a class="classEditLink" name="' + newClassID + '" href="#">Edit</a></td>' +
'<td width="20px"><input type="checkbox" class="chkSelectToDelete" name="deleteClasses[]" value="' + newClassID + '" /></td>' +
'<td>' + classNumberAdd + '</td>' +
'<td>' + classNameAdd + '</td>' +
'</tr>');
if (addDocs == 'true') {
$('#docsTable input[type="checkbox"]:checked').each(function() {
var $row = $(this).parents('tr');
var docID = $row.find('td:eq(0) input').val();
var docName = $row.find('td:eq(1)').html();
var docDescription = $row.find('td:eq(2)').text();
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td></td>' +
'<td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td>' +
'<td width="245px">' + docName + '</td>' +
'<td width="600px">' + docDescription + '</td>' +
'</tr>');
});
//$('#classesTable tbody:last').append('<tr class="classDocsRow"><td></td><td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td><td width="245px">' + docName + '</td><td width="600px">' + docDescription + '</td></tr>');
} else {
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td colspan="4">' +
'<strong>No documents are currently associated with this class.</strong>' +
'</td>' +
'</tr>');
}
return newRow;
}
Aptana Eclipse IDE is reporting an error in two places in the "if (addDocs == 'true')" section: The first error, "missing ) after argument list", is on the second line after "newRow += ..." and the second error "missing ; before statement" is two lines after that. Note that I also have that entire section in one line (not broken up with string concats) commented out shortly after that. That shows only one error, the error about missing a right paren.
If I comment out everything in the if clause and pass addDocs as false, the else clause returns a new row as expected.
This must be simply a js syntactic problem, but I can't see what I'm doing wrong.
Any help will be greatly appreciated!
You are missing the + here:
' + docID + '-' + newClassID + '" /></td>' +
^
The second error is probably just a result of the first error.

Categories