Calling a function in dynamically created button javascript - javascript

I'm trying to create a button with a an onClick that calls a function with the signature deleteEntry(entry). However, I get an error saying that entry is undefined even though I am using it in the same function. I tried adding escape characters but it does not have any effect. Any ideas?
function addToTable(entry) {
var result = "<tr>"
result += "<td>" + entry.id + "</td>";
result += "<td>" + entry.title + "</td>";
result += "<td>" + entry.url + "</td>";
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry +
")\">Delete</button></td>";
result += "</tr>";
$("#table").append(result);
}

You can create the button as a jQuery object and use the on method to listen to the click event. Then when the event listener is attached append the button to the row like the other elements in the function.
Check the code snippet below to see it in action.
// Dummy entry.
var entry = {
id: 0,
title: 'test',
url: 'http://url.com'
}
// Your AJAX call.
function deleteEntry(entry) {
console.log(entry);
}
function addEntryToTable(entry) {
var $id = $('<td>' + entry.id + '</td>');
var $title = $('<td>' + entry.title + '</td>');
var $url = $('<td>' + entry.url + '</td>');
var $button = $('<button class="btn">Delete</button>');
var $buttonWrap = $('<td></td>');
var $row = $('<tr></tr>');
// Add 'click' event listener to the button.
$button.on('click', function(event) {
deleteEntry(entry);
});
$buttonWrap.append($button)
$row.append($id, $title, $url, $buttonWrap);
$('#table').append($row);
}
addEntryToTable(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>

If you inspect this button you generated it will probably have the following attribute: onClick="deleteEntry([object Object])
I think what you want is:
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry.id + ")\">Delete</button></td>";
I guess you have a list variable "entries" somewhere.
In the delete function you can find the clicked entry with the inputed Id.

Related

how to select specific element id from dynamic element ids and pass it as function arguments - javascript?

Upon onclick function other variables pass to another function perfectly but when checking the val() of specific Input field value it gives undefined. I might be wrong it following way
maybe I am not getting the input text field id correctly
No proper way of making the input element id dynamic
element id is not escaping properly
Here is my code
`function addVariable(data, index) {
var datavar = {
itemname : data[index].name,
itemprice : data[index].price,
itemtotal : data[index].price,
itemcounter : data[index].id,
};
addRow(datavar); // creates table and display data + input field
}`
function addRow(datavar){
var inputvalue= 'inputid'+ datavar.itemcounter;
var btn ="<input type='button' onclick='addbill("+datavar.itemprice+","+datavar.itemcounter+",\""+inputvalue+"\");' value='add item' />";
var $table =$('#product_list tbody');
var $row =
$(
" <tr id='parent "+datavar.itemcounter + " '>" +
"<td id='price "+datavar.itemcounter + " '>" + datavar.itemname + "</td>" +
"<td>" + datavar.itemprice + "</td>" +
"<td > <input type='text' id='"+inputvalue+" ' name='"+inputvalue+"' min='1' > </td>" +
"<td>" + btn + "</td>" +
"</tr>"
);
$row.data("itemname",datavar.itemname);
$row.data("itemnprice",datavar.itemprice);
$row.data("itemntotal",datavar.itemtotal);
$row.data("itemntotal",datavar.itemcounter);
$row.data("quantity",inputy);
total += Number(datavar.itemprice );
$('#finaltotal').val(total);
$table.append($row);
}
`function addbill(itemprice,itemid,inputvalue){
var t = document.getElementById(inputvalue).value; // gives undefined in console.log
// var t = $('#' + inputvalue).val(); // same issue as above
// var t = $('#product_list tbody').find('input').val(); // gets first row input value
}
`
upon checking directly as console.log(inputvalue) it gives dynamic id such as inputvalue1 ,inputvalue2, as their respective loop value but I am not able to get the value of input field upon using val() or value

Need help referencing elements

I know I'm asking really simple questions but I'm a beginner and it the process of learning. I've got this code but I don know how to make it work. The output i expect is upon clicking the button it activates function insertAfter and adds text/paragraph that ill write.
I've tried: onclick='insertAfter(test,index.this)'
It didn't work and consoled said it was undefined.
var content = "";
Applications.forEach(generatetable);
function testfn(index, tdElement) {
console.log(tdElement.parentElement);
console.log(index);
console.log(Applications[index].Name);
}
function generatetable(item, index, arrays) {
var columns = "";
columns = columns + "<td onclick='testfn(\"" + index + "\", this)'>" + "<button onclick='insertAfter(test?,???)' type=\"button\">Click Me!</button>" + item.UAID + "</td>";
columns = columns + "<td>" + item.Name + "</td>";
columns = columns + "<td>" + "<a href='www.wahtever.com'>map</a>" + "</td>";
content = content + "<tr>" + columns + "</tr>";
}
var test = "<tr><td>fsdf</td></tr>";
document.getElementById("table").innerHTML = content;
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
It is supposed to insert a paragraph preferably what i put in the test variable but if there is better is better solution please let me know.
<button onclick='insertAfter(test,ElementID)>
The second refference node (ElementID) should be be the id of the element after which it is to be put. So it has to be somehow refferenced for example by id.

Sort HTML Table, that gets appended via JQuery

Hello i'm trying to use Tablesorter(https://github.com/christianbach/tablesorter) to sort a table of mine which i generate throu JQuery.appends. This is how my code looks:
$(document).ready(function() {
*Lotsa more code .....*
$.get("../skillqueue",{keyid: keyid, charid: charid},function(xmlskillqueue){
console.log("XML Skillqueue");
console.log(xmlskillqueue);
//Variables for
var rowsets = xmlskillqueue.getElementsByTagName("rowset");
var skillrows;
for(var i = 0; i < rowsets.length; i++){
if(rowsets[i].getAttribute("name") == "skillqueue"){
skillrows = rowsets[i].getElementsByTagName("row");
}
}
//Defines Table Headers
$("#tableskillqueuelist").append(
"<thead>" +
"<tr>" +
"<th>Order: </th> "+
"<th>Skill Name: </th> "+
"<th>Training to: </th> "+
"<th>Starts:</th> "+
"<th>Ends:</th> "+
"</tr> "+
"</thead>"+
"<tbody>"
);
for(var i = 0; i < skillrows.length; i++){
(function(i, skillrows) {
$.get("../getitemname", {itemid:skillrows.getAttribute("typeID")},function(itemname){
$("#tableskillqueuelist").append(
"<tr> " +
"<td>" + skillrows.getAttribute("queuePosition") + ". " +
"<td>" + itemname + "</td>" +
"<td>" + "|Train to: " + skillrows.getAttribute("level") + "</td>" +
"<td>" + "|Training Starts: " + skillrows.getAttribute("startTime") + "</td>" +
"<td>" + "|Training Ends: " + skillrows.getAttribute("endTime") + "<td>" +
"</tr>"
);
})
})(i, skillrows[i]);
}
//Ends the table body
$("#tableskillqueuelist").append("</tbody>");
});
});
Now i'm wondering what i need to do to have it successfully run the $("#tableskillqueuelist").tablesorter(); method. Since it seems like whenever i try and run it, the #tableskillqueuelist seems to be empty.
You need to tell table sorter that you've changed the data and that you want to sort it by triggering events.
Example from the docs: http://tablesorter.com/docs/example-ajax.html
$("table").tablesorter();
$("#ajax-append").click(function() {
$.get("assets/ajax-content.html", function(html) {
// append the "ajax'd" data to the table body
$("table tbody").append(html);
// let the plugin know that we made a update
$("table").trigger("update");
// set sorting column and direction, this will sort on the first and third column
var sorting = [[2,1],[0,0]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
});
return false;
});
HTH

Removing row refresh page jquery

I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);

how to store array data in table?

I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.
listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);

Categories

Resources