How to pass id of dynamic drop downlist? - javascript

I have dynamic table, in that table every row has a dynamic dropdown list. So every dynamic dropdown list have a unique id, I have to pass this id to the onChange function. Please tell me how to do this. Please see this question for more info.
<select id=carpender"+obj[i].b_id +"onChange='update(this.id)
The data in the table is dynamically generated. I have to pass an id like carpenter12, if the value of obj[i].b_id is 12.
Working code I modified this code
JavaScript:
<script>
function fetchData1(){
$(".data-contacts1-js tbody").empty();
$.get("http://localhost/service/services.php", function(data) {
var obj=JSON.parse(data);
// convert it into obj otherwise it will give
//alert(obj.length);
for(var i in data){
var tr=$("<tr></tr>");
tr.append(
"<td>" + obj[i].b_id + "</td>" +
"<td>" + obj[i].cust_name + "</td>" +
"<td>" + obj[i].cust_mobile + "</td>" +
"<td>" + obj[i].cust_email + "</td>");
tr.append("<select id="+obj[i].b_id+" onChange='update(this.id)' class='input-small'><option value='New Job'>New Job</option><option value='WIP Job'>WIP Job</option><option value='Close Job'>Close Job</option></select>");
$(".data-contacts1-js tbody").append(tr);
i++;
}
});
}
$(document).ready(function(){
$(".data-contacts1-js tbody").empty();
$('#fetchContacts1').click(function() {
fetchData1();
});
});
</script>
<script>
function update(id){
alert(id);
}
</script>

Related

Print Json data in html tabel by javascript

I have JSON data saved in this api https://api.myjson.com/bins/xeza2. I want to print the data in a table by using only JavaScript or jQuery. I have tried a few things. I have used XMLHTTP request. Json.parse() . Every method on stack.
This was the first thing I have tried
$(function () {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function (data) {
$.each(data.info, function (i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" +
"<td>" + f.name + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
data.info is undefined hence why you weren't getting anything added to the table. You need to change it to data.ct_info.
The below code can access the JSON data in your request's response and appends it to the table. I am not sure how you want the data to look or what properties you are trying to access (hence the undefined's) that I'll leave up to you but the below should help get you started.
f.job and f.roll are non-existent properties.
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function(data) {
$.each(data.ct_info, function(i, f) {
var tblRow = "<tr>" + `<td id=${f.id}>` + "</td>" +
"<td>" + f.name + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
var users = []
//GET USER INFO
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
$.each(users, function(i, user) {
var userRow = "<tr>" + `<td id=${user.id}>` + "User's Name:" +
"</td>" +
"<td>" + user.name + "</td>" + "</tr>"
$(userRow).appendTo("#userdata tbody");
})
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<tbody>
</tbody>
</table>

onClick function within another function

I'm fairly new to JS and hoping someone can help me with an issue I'm having while I'm trying to build a demo gallery. I have a JSON file called feed.js and I'm calling certain fields in that JSON file (i.e. the image URL) into a HTML table and that's working no problem. What I'm trying to do next is that when a user clicks on the image the, the cells beside the image populate with more fields called from the JSON file. This is what I have so far but myFunction is outside f is defined so I'm getting "Uncaught ReferenceError: f is not defined" when I click the image. Any ideas of how to get around this would be great! Sorry if this is a real novice question but as I said I'm a newbie!
<script>
$(function() {
var feed = [];
$.getJSON('feed.json', function(data) {
$.each(data.phones, function(i, f) {
var tblRow = "<tr>" + "<td><div id=\"demo1\"><img onclick=\"myFunction()\" id=\"demo\" src=" + f.image + "></div></td></tr>";
$(tblRow).appendTo("#userdata tbody");
});
});
});
function myFunction() {
document.getElementById("demo1").innerHTML = "<tr>" + "<td><div id=\"demo1\"><img onclick=\"myFunction()\" id=\"demo\" src=" + f.image + "></div></td><td>"+ f.description + "</td><td>" + f.manufacturer + "</td></tr>;"
};
</script>
Rather than using an onclick, you should set a jQuery event listener on the target element from within the function scope that you're defining myFunction. Since you're img has an id, you can target it in that manner. Something like this:
<script>
$(function() {
var feed = [];
function myFunction() {
document.getElementById("demo1").innerHTML = "<tr>" + "<td><div id=\"demo1\"><img id=\"demo\" src=" + f.image + "></div></td><td>"+ f.description + "</td><td>" + f.manufacturer + "</td></tr>";
}
$.getJSON('feed.json', function(data) {
$.each(data.phones, function(i, f) {
var tblRow = "<tr>" + "<td><div id=\"demo1\"><img id=\"demo\" src=" + f.image + "></div></td></tr>";
$(tblRow).appendTo("#userdata tbody");
});
});
$(document).on('click', '#demo', myFunction); // everytime the user clicks on an element with id #demo inside the document, myFunction will be called
});
</script>
on this line
var tblRow = "<tr>" + "<td><div id=\"demo1\"><img onclick=\"myFunction()\" id=\"demo\" src=" + f.image + "></div></td></tr>";
you are setting common id to each row into your table, change this.
secondly,
remove '\' from your structure, this is endLine character.
this might be what you are looking for..
$.getJSON('feed.json', function(data) {
$.each(data.phones, function(i, f) {
var tblRow = "<tr>" + "<td><div><img onclick='myFunction()' src=" + f.image + "></div></td></tr>";
$(tblRow).appendTo("#userdata tbody");
});
});

Issue regarding ajax and identifying data from a table

I'm desperately trying to gain access to the $BarcodeID by pressing the DELETE button on my site. All I want to do is retreive this 13 digit number, so that I can use it to remove that row from the item Database (Sql).
I know that as long as I get the correct row I can get the data but i'm wondering if thats even possible because I'm building the table inside a $.post().
Please note that before i started trying to make the button and get the barcodeID in the click function all of the code was working. Thanks!
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr><td id='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".delete").click(function(){
// var BarcodeID = $(this).closest('tr').find('#rowbarcode').val();
var BarcodeID = $(this).parent().find("#rowbarcode").text();
var $row = $(this).closest("tr"); // Finds the closest row <tr>
var $tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
console.log($tds);
//all I want is $BarcodeID
});
});//eof
Image of table on site:
Just for anyone who's interested I found a pretty neat way of solving my problem. Thanks to everyone who helped #Pointy #Taplar #Andreas. What I needed was 'event binding on dynamically created elements'. It is particularly useful when linked with $.post and $.get operations as they complicate data retreival.
Sample output to console:
5000157024671 <- if i clicked the first delete button
6221033101517 <- if i clicked the second delete button
Next stage:
As this is only a reference to a barcode number which has to be removed from the DB I will now pass this onto php via a post operation.
Next part of my project (adding a row search feature) can be found here:
Dynamically created table queries
Sample solution code:
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
//from here down is the relevant code
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr class='row'><td class='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".contenttable").on('click', '.delete', function(){
var BarcodeID = $(this).closest('tr').find('.rowbarcode').text();
console.log(BarcodeID);
});
});//eof

Add HTML code inside of a JS var that contains an HTML element

I need to add a list of task after to click one row in a html table I'm using knockout js. the problem is that I'm just adding de last task from my data in a row and I need to add a new TR inside my element "$taskSelected" for each task. Here is my code
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
$.each(data, function(key, value) {
var html = "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
$taskSelected.innerHTML=html;
});
}).fail(function() {
alert("error");
});
};
}
the var $taskSelected contains another row "<tr> </tr>" basically Ii want to nested rows. Some advises please
Try this:
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
var html = "";
$.each(data, function(key, value) {
html += "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
});
$taskSelected.innerHTML=html;
}).fail(function() {
alert("error");
});
};
}
All I did was move var html outside of your each loop. This makes sure that all your previous HTML stays inside the variable, otherwise you are overwriting html each time you run through the loop (This is why you're only outputting the last one ;) ).

adding text-box in column (script)

I have this code
(in script):
var response = [{
"A":"a2",
"B":"b2",
"C":"c2"
},
{
"A":"a3",
"B":"b3",
"C":"c3"
},
{
"A":"a4",
"B":"b4",
"C":"c4"
}];
$.each(response, function(i, item) {
$('<tr>').html(
//"<tr>" +
"<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody');
});
and I want to change one of column (just for exp it's will be "A") to be "edited" by text-box.
I am tring this:
... `"<td><input type="text">" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody');`...
but it's not working.
any help please!
If i understood correctly,
Instead of creating <tr>, later adding contents to it using html() and finally appending to do the <table>, you can directly add everything altogether to the <table> using append() method.
$.each(response, function(i, item) {
$('#MyTable tbody').append("<tr>"
+"<td><input type='text' value='"+ response[i].A +"'/> </td><td><input type='text' value='"+ response[i].B +"'/></td><td><input type='text' value='"+ response[i].C +"'/></td>"
+ "</tr>");
});
Try saying This
var firstcell = "<td><input type="text" value="VALUE"</td>";
firstcell = firstcell.replace('VALUE', response[i].A);
Use this for first cell in each Row. After that append this in whole row.

Categories