Dynamic anchor tag inside <td> - javascript

I have a table and for one of the <td> I want to generate the <a> tags dynamically using JavaScript.
Writing a small snippet of the code.
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var item in list)
{
<tr>
<td>...</td>
<td>...</td>
<td> MyFunction(item.Parameter1) </td> // dynamic anchor tag
</tr>
}
</tbody>
</table>
JavaScript function.
MyFunction(Parameter1)
{
var aTag = "";
.....
..... //some formatting as per needs
aTag = '<a id="' + someId + '" alt="' + someAlt + '" title="' + someTitle + '" style ="color:Blue;text-decoration:underline;" href="#" onclick="fnAnotherFunction(' + P1 + ',' + P2 + ');">' + NameofTheTag + '</a>';
return aTag;
}
How can the string returning aTag form an <a> tag at the <tr> <td>..?
Is this possible or is their a better solution to this.

You could use .append() or .appendTo()
$('selectorForTD).append(MyFunction(item.Parameter1))`
or
var anch = MyFunction(item.Parameter1);
anch.appendTo($('selectorForTD');
I think this is what you're after.
Edit:
Since you're using jQuery, you could create your anchor element like:
MyFunction(Parameter1)
{
// var aTag = "";
.....
..... //some formatting as per needs
var aTag = $("<a>",{id:someID, alt:someAlt, title:someTitle}).css({ ...cssRules...}).click(function(e)
{
fnAnotherFunction(P1,P2);
});
return aTag;
}
Here's a quick fiddle to illustrate.

Related

get the child key for specific value when append table using Jquery

i created a table and used Jquery to put all the user database from firebase info in it. The problem is: i have a button in the table that be should when you click the button console print the element key from database.
var userDataRef = firebase.database().ref("User/3N2f2rJSSAZmFOdZEeJdlsuEZam2").orderByKey();
userDataRef.on('child_added', function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var title_val = childData.Title;
var url_val = childData.Url;
// Append data
$("#data").append("<tr><td>" + title_val + "</td><td><a href=" + url_val + " target='_blank'> <button class='box'>GO</button></a></td><td><button id='del' class='box'>Delete</button></a></td><</tr>");
$('#data').on('click', '#del', function(){
console.log(key)
});
<table border="0" style="height: 63px; width: 100%;">
<thead>
<tr>
<div class="column middle" style="background-color:#f8f8f8;">
<td>Title</td>
<td style="width: 40%;" >Link</td>
<td style="width: 10%;" >Delete</td>
</div>
</tr>
</thead>
<tbody id="data" >
</tbody>
</table>
when this function perform i gut all the keys not just the one from the exact raw
$('#data').on('click', '#del', function(){
console.log(key)
});
output :
-LkT_afLi9nfn65OS2QJ database.js:17:17
-LkTciKQVEa2bsbtSwkW database.js:17:17
-LkTclDO8dYSBfgiBjAZ
You are binding to all the elements and you are duplicating ids. Ids are singular.
You would be better off with either binding to the one button alone or event delegation with a data attribute.
userDataRef.on('child_added', function(childSnapshot) {
/* cut out the vars */
var myRow = $("<tr><td>" + title_val + "</td><td><a href=" + url_val + " target='_blank'> <button class='box'>GO</button></a></td><td><button class='box'>Delete</button></a></td></tr>");
myRow.find("button").on("click", function(){
console.log(key)
});
$("#data").append(myRow);
});
or event delegation with a data attribute
$("#data").on("click", "button[data-key]", function(evt){
var btn = $(this);
console.log(btn.data("key"))
});
userDataRef.on('child_added', function(childSnapshot) {
/* cut out the vars */
var myRow = $("<tr><td>" + title_val + "</td><td><a href=" + url_val + " target='_blank'> <button class='box'>GO</button></a></td><td><button class='box' data-key='" + key + "'>Delete</button></a></td></tr>");
$("#data").append(myRow);
});
ID's should never be repeated, use the class of the buttons instead as a common attribute.

jQuery function - set String parameter

I am creating a web page and I want to give a alert whenever I clicked a row of the generated table that is generated by the below code. In order to do that I am using setAlert(message) function.
My problem is that it only works when the parameter that is set to the function is a integer. it doesn't work when it is a String.
Help me solve this problem.
Thank you.
function getItemList(){
$('#tableItem').empty();
$.ajax({
url: 'ItemServlet',
data:{version:2},
type: 'post',
dataType: 'json',
success: function (data) {
$('#tableItem').append('<table class="table table-striped table-hover" id="table1">\n\
<thead><tr><th class="table-text-align-centre" style="width:10%">Item Code</th>\n\
<th class="table-text-align-centre" style="width:20%">Name</th>\n\
<th class="table-text-align-centre" style="width:50%">Description</th>\n\
<th class="table-text-align-centre" style="width:10%">Stock Count</th>\n\
<th class="table-text-align-centre" style="width:10%">Active</th></tr></thead><tbody class="table-hover"></tbody></table>');
var length = data.length;
for (i = 0; i < length; i++) {
var post = data[i];
$('#table1').append('<tr onClick="setAlert('+post['itm_code']+')"><td>' + post['it_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_description'] + '</td> \n\
<td class="table-text-align-centre">' + post['itm_stockcount'] + '</td> \n\
<td class="table-text-align-centre">' + post['active'] + '</td> \n\
</tr>');
}
}
});
}
function setAlert(message) {
var id = message+ "";
alert(id);
}
The issue here is that you are passing your parameters into the setAlert function without defining the quotes. Now because you are using " to define your onClick and your using ' to formulate you html, you need to use an apostrophe escaped \' to pass in the parameter.
So currently, if post['itm_code'] is 1, it will generate the following html with valid javascript:
<tr onClick="setAlert(1)"><td>
However if post['itm_code'] is a string "my string", it will render the following html with invalid javascript:
<tr onClick="setAlert(my string)"><td>
So the following line:
<tr onClick="setAlert('+post['itm_code']+')"><td>
should be changed to:
<tr onClick="setAlert(\''+post['itm_code']+'\')"><td>

Append datatables success but thead section gone

I'm try to use append to fill my table. Please take a look
<table width="100%" id="tbltbl" class="asoy table table-bordered table-striped">
<thead>
<tr>
<th width="1%">No</th>
<th width="14%">Outlet</th>
<th width="14%">Leader</th>
<th width="14%">Chief</th>
<th width="14%">RM</th>
<th> Action </th>
</tr>
</thead>
</table>
for default my table look like this
I run the onchange method and i receive this
[{"OutletCode":"K-BDIP3","Description":"BANDUNG INDAH PLAZA 3","NipLeader":"0802400","NipRM":"0802678"
,"NipChief":"-"},{"OutletCode":"K-CMHM2","Description":"KIOS CIMAHI MALL 2","NipLeader":"0802400","NipRM"
:"0802678","NipChief":"-"},{"OutletCode":"K-TSPA3","Description":"TASIK PLAZA ASIA 3","NipLeader":"0802400"
,"NipRM":"0802678","NipChief":"-"},{"OutletCode":"K-BDCW2","Description":"KIOS BANDUNG CIWALK 2","NipLeader"
:"0802400","NipRM":"0802678","NipChief":"-"}]
then i append it
function byarea(){
$(".asoy").empty();
var area = $("#pilihanarea").val();
var tipe = $('#tipe').val();
var formUrl = "<?=base_url();?>arealeader/finddata";
var angka = 1;
$.ajax({
url: formUrl,
type: 'POST',
data: {tipe:tipe,area:area},
success: function(data, textStatus, jqXHR){
var newdata = JSON.parse(data);
$.each(newdata, function(key, val) {
$('.asoy').append('<tbody><tr> <td>'+ (angka++) +'</td>' +
'<td>' + val.OutletCode + '</td>' +
'<td>' + val.NipLeader + '</td>' +
'<td>' + val.NipChief +'</td>' +
'<td>' + val.NipRM +'</td>' +
'<td>----</td>' +
'</tr></tbody></thead>');
});
}
});
}
and my table look like this
It seems I'm loosing my <thead>..</thead> section. Any solution for this ? thanks in advance...
Create an empty <tbody class="asoy"></tbody> just before the closing </table> tag and remove the class "asoy" from the <table> tag. Then remove the <tbody> tags from your call to append().
At the moment, your $(".asoy").empty(); is removing the entire table contents but you only want to clear the body, not the headers. Creating a <tbody> tag solves that problem while still allowing your function to be re-entrant (i.e. you can run it again later and it won't duplicate the contents).
Based on your code
$('.asoy').append('<tbody>
<tr> <td>'+ (angka++) +'</td>' +
'<td>' + val.OutletCode + '</td>' +
'<td>' + val.NipLeader + '</td>' +
'<td>' + val.NipChief +'</td>' +
'<td>' + val.NipRM +'</td>' +
'<td>----</td>' +
'</tr>
</tbody>
</thead>'); // <--- What this tag for?
I'm not sure but I think its a wrong tagging.
tbody should not be inside a thead unless your
header will consist of another table element

Loop through a form which contains another form

I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>
nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."

Each function in jquery not looping

I have a table with the below values using django.
<tr>
<td>Chips</td>
<td>2</td>
<td>20.00</td>
<td id='totalperitem'>40.00</td>
</tr>
<tr>
<td>pizza</td>
<td>2</td>
<td>100.00</td>
<td id='totalperitem'>200.00</td>
</tr>
<tr>
<td>Peanut Butter</td>
<td>2</td>
<td>50.00</td>
<td id='totalperitem'>100.00</td>
</tr>
I'm trying to get the total of the totalperitem column using the jquery 'each' function. However , i'm only getting the value of the first item.
jquery syntax:
$('#totalperitem').each(function () {
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
this is the output im getting in the console
sum : 40
What am i doing wrong?
Thanks,
KJ
Multiple elements with same ID are not allowed in one page.
Use class instead of id
<td class='totalperitem'>200.00</td>
And use .totalperitem as selector.
var running_total = 0;
$('.totalperitem').each(function(){
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
Use class instead of id and do,
var sum = $('.totalperitem').get().reduce(function(a,b){
return a + parseFloat(b.innerHTML);
},0);

Categories

Resources