Get value of first <td> element in same row as input button - javascript

I am trying to get the text from the first td tag from each row by using the input button as shown below:
for(var i in obj.questions){
question += '<tr class="row">';
question += "<td>"+ obj.questions[i].question+"</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
document.getElementById("t01").innerHTML = question;
}
The id=t01 is for the table tag. Here is the js that I tried working on but is not working:
var question;
$('.question').click(function() {
question = $(this).parent().find('td:first-child').text();
});

You have to iterate through each row like below
$('.question').click(function () {
$('#t01 .row').each(function () {
console.log($(this).find("td:first-child").text());
});
});
Also I would suggest to write html use jQuery instead of javascript instead of document.getElementById("t01").innerHTML
$('#t01').html(question);
Also your implementation of creating rows dynamically have one problem , you will get only one row every time. You can change your code like below
var question = "";
for (var i in questions) {
question += '<tr class="row">';
question += "<td>" + questions[i].question + "</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
}
$('#t01').html(question);
I have created a running sample for you
https://stackblitz.com/edit/jquery-n4spxc?file=index.js

You may need to use .live() to achieve this, depending on the order of your event binding and HTML generation. Also, consider revising your click event logic so that you iterate over all rows of the table to access the text of "first cell" for each table row:
// When the .question input is added to the DOM, this event logic will
// be bound to the input element automatically
$(document).live('.question', 'click', function() {
var question;
// Iterate over each row of the table
$('#t01 .row').forEach(function() {
// For each row, extract the text from first row cell
var row = $(this);
var firstCell = row.find('td:first-child');
var firstCellText = firstCell.text();
// Not sure how you want to use the data, this shows
// how to construct a comma separated string of text
// from all first row cells
question += firstCellText + ',';
});
// Print result to console
console.log(question);
});

Related

textarea clears when using innerhtml [duplicate]

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.
If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.
if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
var _row = "<tr id='queue_row_" + items_in_queue + "'>";
_row += "<td>";
_row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
_row += "</td>";
_row += "<td>";
_row += _item;
_row += "</td>";
_row += "</tr>";
document.getElementById("upload_queue").innerHTML += _row;
document.getElementById("upload_image_" + items_in_queue).style.display = "none";
items_in_queue++;
document.getElementById("uploader_holder").innerHTML +=
'<input id="upload_image_' + items_in_queue +
'" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' +
'onchange="add_to_upload_queue()" style="display: inline;" />';
}
Yeah... you're going to want to use appendChild instead of modifying the inner HTML:
var myInput = document.createElement("INPUT");
// do stuff to my input
var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);
That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

Hide dynamically created HTML element with JQuery

I am creating a table row with a "spinner" to show actions when a button is pressed.
I append the row id to the spinner's id to be able to target it specifically.
For example row 21: #spinnerAction-21
While iterating through the data set, I add the name to array, so I can hide all of them after the html is inserted into the page.
Though I can't get my spinners to hide.I tried using inline CSS visibility to hidden but I couldn't un-hide it when I was done.
Any help on hiding my spinners? Is there a better way to do this?
var spinnerArray = $.makeArray();
for (var i = 0; i < data.length; i++) {
html += '<tr>';
html += '<td>';
//other html output
html += '<i class="fa fa-spinner fa-spin" id="spinnerAction-' + data[i].entry_id + '" style="font-size:24px;color:dodgerblue;"></i>';
html += '</td>';//end button comlumn
html += '</tr>';//end row
//Add a reference to the spinner for that row to hide.
spinnerArray.push("#spinnerAction-" + data[i].entry_id);
}//end for
// insert the html rows
$('#display_info').append(html);
//hide the spinner in each row
$.each(spinnerArray, function (index, val) {
$(val).hide();
});
For anyone else running across this post, I ended up replacing
spinnerArray.push("#spinnerAction-" + data[i].entry_id);
with
spinnerArray.push("spinnerAction-" + data[i].entry_id);
Removing the #
Then adding the # back in the
$.each(spinnerArray, function (index, val) {
$('#' + val).hide();
});

Javascript function for adding row to html table does not work

I developed two javascript functions which create a html table (showList4() ) and which add rows (addRow() ), pls see code below. showList4() works fine, but addRow() does not; addRow() adds row, but:
(error 1): the row is not added straight under the previous row, but shifted to the left.
(error 2): executing addRow the second time does not put the row after/under the previously added row, but before/above it.
For adding a row I looked at the solution at Add table row in jQuery but I dont know where I go wrong with the addRow() code?
javascript code:
function showList4(title, wrapper, wrappermethod, tableid){ //this functions works fine
if((!$('#'+wrapper).length) ){//no action if no info or invalid wrapper agurment type
return;
}//if
var form = '<table id="'+tableid+'">';
//add title
if(typeof title === 'string'){
form += '<caption> '+ title +' </caption>';
}//if
form += '<tbody>';
var nrofrows = arguments.length - 4;
console.log('Showlist3- nrofrows: '+nrofrows)
//add following rows with vert labels in first colum and datavalues in following columns
for(var row=0;row<nrofrows;row++){ //for each following row
form += '<tr> <td> ';
for(var column=0, column_max=arguments[4+row].length;column<column_max;column++){
if(arguments[4+row] !== undefined){
form += '<td>' + arguments[4+row][column] + ' </td>';
}//if
}//for(var column=0, column_max=labels_hori.length;column<column_max;column++){
form += '</tr>';
}//for(var i=0,i_max=labels_hori.length;i<i_max;i++
form += '<tr><td> </tr></td> </tbody> </table>'; //add empty line and finish table
switch(wrappermethod){
case 'html':
$('#'+wrapper).html(form);
break;
default: //no action if invalid wrapper argument
break;
};//switch
return;
};//showList4()
function addRow(tableid,values){
var form = '<tr>';
for(var i=0,i_max=values.length;i<i_max;i++){
form += '<td>' + values[i] + '</td>';
}//for
form += '</tr>';
$('#'+tableid+' > tbody:last').after(form); //reference example code: https://stackoverflow.com/questions/171027/add-table-row-in-jquery
//$('#'+tableid+' tr:last').after(form); //reference example code: https://stackoverflow.com/questions/171027/add-table-row-in-jquery
return;
}//addrow
$(document).ready(function(){
showList4('Title table','myDivid','html','myTable',
['Some text1','Some text2','Some text3','Some text4'],
['1','2','3','4']);
addRow('myTable',['A','B','C','D']);
addRow('myTable',['E','F','G','H']);
});//$(document).ready(function(){
html code:
<div id="myDivid" style="width:500px; "> </div>
There are a few things wrong with your code.
First, you are targeting the "last body tag" rather than the "last row in the body". So change your line
$('#'+tableid+' > tbody:last').after(form);
to
$('#'+tableid+' > tbody > tr:last').after(form);
This will ensure that the new row is inserted within the body of the table.
Second, you are creating an additional cell in your first two rows. See this line
form += '<tr> <td> ';
Change it to
form += '<tr>';
Third, you have broken html on this line
form += '<tr><td> </tr></td> </tbody> </table>'; //add empty line and finish table
Change it to
form += '<tr><td colspan="4"></td></tr></tbody> </table>'; //add empty line and finish table. NOTE the colspan to format the table correctly.
Here is a working version at jsbin
p.s. jsbin suggest some other fixes to missing semi-colons, misuse of the switch statement and unnecessary semi-colons.

How do I create HTML table using jQuery dynamically?

I am trying to create a HTML table like the following dynamically using jQuery:
<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>
This is my actual table :
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
This is the method which will create tr and td elements taking id and labelText:
function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);
// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}
I also have a value which will be shown as tool tip.
Please help me to create a table dynamically with tool tip and tr td.
EDIT:
I have almost done with the following code:
function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
Here label is coming properly and the input box is not coming and it shows [object Object] where the text box has to come...
When I printed the textInputBox using console.log, I get the following:
[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
What could be the issue?
Thanks to #theghostofc who showed me path... :)
You may use two options:
createElement
InnerHTML
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Edit:
Check Dynamic creation of table with DOM
Edit 2:
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.
It's much easier to construct just the html and change the id s of the label and input according to your needs.
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}

html table editable and non-editable cells with jQuery

Is there a plugin or way to make certain table columns (not rows) editable and others not editable
with jQuery?
I have seen plugins for clicking on a cell to make it editable, but I mean explicitly making a cell/column editable or not.
I have a way of doing it but it feels like a bit of a hack job.
Here is my function for making a column editable:
function isEditable(rowArray, headersArray)
{
var counter = 0;
var notEditable = ['product code', 'product'];
for(i in rowArray){
counter = 0;
data = headersArray[i].toLowerCase();
for(a in notEditable){
if(data == notEditable[a]){
counter++;
}
}
if(counter > 0){
rowArray[i] += 'notEditable';
}
}
return rowArray;
}
it compares the header of the cell to an array of predefined values which = a non-editable column.
Then I build the row:
function buildHTMLTableRow(row, mutable)
{
output = '';
output += '<tr>';
for(var i = 0; i < row.length; i++)
{
value = trim(row[i]);
if(mutable){
index = value.indexOf('notEditable');
if(index != -1){
value = value.substring(0, index);
output += '<td>' + value + '</td>';
}
else{
output += '<td><input size="5" type="text" value="' + value + '" /></td>';
}
}
else{
output += '<td>' + value + '</td>';
}
}
output += '</tr>';
return output;
}
The mutable parameter decides if the row is editable or not, and the indexOf('noteditable') decides for the cell(but pretty much column) from the isEditable function.
Is there a plugin that does this better, or should I just settle with what I have?
Visit this jsFiddle link: Disable Columns
Following is the data flow:
I have created a row Array named "rowsD". When page loads I am populating my table (id=myData) with these rows.
Now creating another array called disableHeaders wherein I am passing the headers,
which you need to disable entire columns.
I am calling function disableFields passing disableHeaders as parameter
In the function, first I am fetching the index of the header whose value is equal to the values in headers array
If I find one, then from Input tag I am extracting the Value attribute using $(this).find('input') selector
Finally I am replacing the current child with Label tag passing the extracted Input tags Value
You may also comment out disableFields(disableHeaders); line to actually see, how table gets rendered initially
Thank you

Categories

Resources