Getting id of dynamically created row - javascript

In a table of id productTable, I am adding rows using the following jquery code:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
}
and I'm attaching a handler to these rows using:
$("#productTable").on("click","tr",function(event){
alert(this.id);
});
but the ID that I'm getting is of the table whereas I want the id of the row that is being clicked.
Help

The issue is with what you're appending, it's not valid HTML
$('#productTable').append(
'<tr id=' + result.productArray[i].productID + 'class="product">
<td>
<a> '+result.productArray[i].productName+'</a>
</td>
</tr>'
);
look very carefully, there's no quotes around the ID, and no space separating the ID and the class.
Basically you end up with
<tr id=idclass="product">
<td>
<a>text</a>
</td>
</tr>
The correct code would be
$('#productTable').append('<tr id="' + result.productArray[i].productID + '" class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');

Try This:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
var obj = $('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$(obj).click(function(event){
alert($(this).attr("id"));
});
$('#productTable').append(obj);
}

Bind Event when you creating element dynamically. This is another way to do what you want.
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=" + result.productArray[i].productID + " class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$('#'+result.productArray[i].productID).bind('click',function(){
//put your code here
});
}
Demo

Related

Add rows to an empty tbody element

I have table like this:
<table id="search-table" class="table">
<thead>
<tr>
<th>Something</th>
<th>Something2</th>
<th>Something3</th>
<th>Something4</th>
<th>Something5</th>
</tr>
</thead>
<tbody></tbody>
</table>
I have an API call which returns data that I want to put as row and columns in the empty tbody element.
var body = document.getElementsbyTagName("tbody");
var x = 0;
for (i = 0; i < APIcall.length; i++) {
var createRow = body.insertRow();
for (j = 0; j < 7; j++) {
var x = createRow.insertCell(j);
}
}
If I insertRow on the thead element the rows are created, but not when I try to add it to tbody. Probably me just misunderstanding something. Any suggestions what I should do?
you're almost there.
First, as Rory mentioned, you're not targeting the tbody in DOM.
You can fix that by replacing the first line with this:
var body = document.querySelector('#search-table tbody')
What that does, is this: It looks for an element with an ID of search-table and a descendant <tbody> and returns a reference.
Your code would run without an error then, but I'm confused about the result.
In the second line, you have var x = 0 but later on I can see var x = createRow.insertCell(j); also. (The second x would give you a reference to a new <td> element).
Hope that helps.
var html ='';
for (i = 0; i < APIcall.length; i++) {`enter code hereenter code here
html += '<tr><td>' + APIcall[i].somthing + '</td><td>'+ APIcall[i].somthing + '</td>' +
'<td>' + APIcall[i].somthing + '</td>' + < td > '+APIcall[i].somthing+' </td>'+
'<td>' + APIcall[i].somthing + '</td></tr>';
}
$('#search-table > tbody').append(html);
enter code here
If you have more than one tbody in your markup, you have to target your's specifically because getElementsByTagName returns an array of elements.
for eyample:
var tbodies = document.getElementsbyTagName("tbody");
var targetTbody = tbodies[0];
or you could loop over tbodies if you want to add your stuff to multiple tbodies.

Creating a list of students and assigning a function to each button

I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});

Why are my rendered elements outside the select tag?

I am trying to append html to a Content Holder in a dialogue box and as you can see by the image, Mile, Meter and Kilometer are outside the select dropdown. Why is this?
var rows = $('#jqxUOMRelatedUnitsDropdownGrid').jqxGrid('getrows');
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").html('<select id="listNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder">');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.UOMRelatedUnit_AddItem) {
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
}
}
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
<div id="divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder"></div>
Because you are appending into the <div> and not the <select>. Do this way:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder select").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
// --------------------------------------------------- ^^^^^^
And you cannot do:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
That's invalid! Either store everything in a tempAppend string and then use:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append(tempAppend);

Calling multiple functions to generate textboxes on same page

I am calling two separate functions to generate dynamic textboxes one of the function works fine whereas other doesn't work though the code for generating textboxes is same except the variables names and label names. Could anyone please let me know what I am doing wrong and how can i figure out this ?
this is the function which is not working.
var C = 3;
var matrixArray = ["question", "mrank"];
$("#addMatrix").click(function () {
for(var j = 0; j < matrixArray.length; j++){
createMatrixInput(MatrixArray[j]);
}
C++;
});
function createMatrixInput(l){
var tb_Div = $('#TextBoxes');
var mstr = '<div class="control-group">';
mstr += '<label class="control-label">' + l + " " + C + '</label>';
mstr += '<div class="controls">';
mstr += '<input type="text" id="' + l + '_' + C + '" name="'+ l +'_' + C + '" />';
mstr += '</div>';
mstr += '</div>';
tb_Div.append(mstr);
};
this is my jsfiddle with complete code.
http://jsfiddle.net/qqqyC/2/
There are 2 problems. The button id is addmatrix and the array is matrixArray, not MatrixArray. The method should look like:
$("#addmatrix").click(function () {
for(var j = 0; j < matrixArray.length; j++){
createMatrixInput(matrixArray[j]);
C++;
}
});
I've spotted a error in your JSFiddle see the id of your button "matrix button" it is addmatrix and you are binding the onClick event to addMatrix and javascript event binding via ID is case sensitive, so the event will not be bind.
Maybe this will solve your whole problem, because it was preventing to execute the click event.

Why is my application not working in IE?

I create a table programmatically in javascript like this and do a innerhtml on a div. It works fine in firefox but IE screws things up. Obviusly the sucker exists in IE. But when I inspect the thing in IE8 I see that a class and a id on link element is without ", but they should be there. Can these be the problem?
var create_table = function(rows, len, bilder, texter, mediaids, url) {
var table = '<table>';
for (var i = 0; i < len; i++) {
if (i % rows == 0) {
table += '<tr>';
}
table += '<td><h4><a id="' + mediaids[i].toString() + '" class="medialinks" href="#" >' + texter[i].toString() + '</a></h4><img src="' + bilder[i] + '" ><td>';
if (i % rows == rows) {
table += '</tr>';
}
}
table += '<table>';
return table;
}
Can anyone spot an error?
I don't know if you are want to validate XHTML or HTML, but here are the errors I spotted :
your are missing a / to close table, should be </table> not <table>
same error for <td>
<img> should be closed too />

Categories