Two tables from one String variable of HTML - javascript

An AJAX query returns an HTML string that has 2 tables.
I want to put table1 into div1 and table2 into div2
If the HTML representing both tables (they're sequential, not nested or anything funny like that) is stored in variable twoTables, how can I use jQuery selectors (or any other method, although I am trying to avoid direct string manipulation) to split up the variable?
edit: data looks like
<table id="table1"> ... </table><table id="table2"> ... </table>

You can split the two tables into an array. Check out the following:
var s = "<table>Dude!</table><table>What?</table>";
var a = s.match(/<table>.*?<\/table>/gi);
alert(a);
So table one will be in a[0], and table two in a[1].

var $tables = $(twoTables);
$('#div1').append( $tables[0] );
$('#div2').append( $tables[1] );
Example: http://jsfiddle.net/VhAzV/
Since twoTables represents an HTML string of 2 sequential tables, just send the string to a jQuery object, then select each table DOM element by its zero based index.
Or you could use .eq() to get the table wrapped in a jQuery object.
var $tables = $(twoTables);
$tables.eq(0).appendTo('#div1');
$tables.eq(1).appendTo('#div2');
Here's a no jQuery version that still uses the browser's native HTML parser:
Example: http://jsfiddle.net/patrick_dw/VhAzV/2/
var twoTables = '<table><tr><td>table one</td></tr></table><table><tr><td>table two</td></tr></table>';
var $tables = document.createElement('div');
$tables.innerHTML = twoTables;
document.getElementById('div1').appendChild($tables.firstChild);
document.getElementById('div2').appendChild($tables.firstChild);
EDIT: Made it truly no-jQuery in the DOM insertion.

As per http://api.jquery.com/load/
$('#result').load('ajax/test.html #container');
You can do this twice for two tables.

If you have a string that looks something like this:
var foo = "<table><tr><td>1</td></tr></table><table><tr><td>2</td></tr></table>";
First make it a jQuery object:
foo = $(foo);
Then you can get each table and insert them wherever you'd like:
$("#div1").append(foo[0]); // First table
$("#div2").append(foo[1]); // Second table

This might be ugly but it's the first thing that comes to my mind, hopefully others will find a more elegant solution:
var tableEnd = '</table>';
var arr = twoTables.split(tableEnd);
var t1 = arr[0].concat(tableEnd), t2 = arr[1].concat(tableEnd);
div1.innerHTML = t1;
div2.innerHTML = t2;
bonus: no jQuery overhead! :)

Related

How to get string representation of dynamically created element

So I have some javascript code that creates a table row by generating a string and appending it to the table. Something like this:
var str = '<tr><td>Column</td><!--More columns--></tr>';
$('#my-table').append(str);
There is one element (an input) in the row that has a LOT of attributes. This is hard to read as a long string so I want to create this one particular element a different way - using $() and passing in attributes as an object as documented here - and then concatenating it with the string above. So I tried to do something like this:
var el = $('<input>', {
type: 'text',
name: 'some_name'
});
var str = '<tr><td>test</td><td>'+el.html()+'</td></tr>';
$('#my-table').append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my-table">
</table>
This should (I thought) create a textbox as the second column in the table but it doesn't work. I just get a empty cell and no errors. What am I doing wrong? Or what should I do?
var $input = $('<input>', {
type: 'text',
name: 'some_name',
/* ... more attributes ... */
});
var $tr = $("<tr>").appendTo('#my-table');
var $td = $("<td>").append($input).appendTo($tr);
// possibly do other things with $input, $tr, and $td
That being said, you really should not build complex HTML with jQuery. It's cumbersome, leads to unreadable and ultimately buggy, hard-to-maintain code. (Even more than that, you really should not build HTML by concatenating strings.)
Build a data structure (an array of objects) and then let an HTML templating library do the work. There are quite a few mature libraries to choose from, handlebars.js being a prominent one. It will pay in the form of much cleaner Javascript code to use one of them.
jQuery html() is the innerHTML not the outerHTML. You want the latter.
var el = $('<input>', { type: 'text', name: 'some_name' });
var str = '<tr><td>test</td><td>'+ el[0].outerHTML +'</td></tr>';
$('#my-table').append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my-table"></table>
you want the Value from input, not the inner html. Try this:
var str = '<tr><td>test</td><td>'+el.val()+'</td></tr>';

How to write out HTML from ajax call using JS

This might seem a little simple, but i've tried many ways & non of them are working as expected.
i have values coming in from an ajax call, & i am displaying these to a <table>.
the data will not be seen at first (css - display:none) but onclick involves a function which displays a dialog of said data.
writing out the data in these ways does not work:
var text = "Example Data<br>";
var text = document.createTextNode("Example Data" + document.createElement('br'));
var text = document.createTextNode("Example Data");
text += document.createElement('br');
The latter outputs [object Text][object HTMLBRElement]
How do i write this correctly??
You can't concatenate node objects (trying to do so with + will convert them to strings first).
Find the element you want to append the nodes you've created, and call appendChild on it repeatedly.
var text = document.createTextNode("Example Data");
someElement.appendChild(text);
someElement.appendChild(document.createElement('br'));
You need to append the line break as an HTML element "createElement" as it is an HTML element.
var text = 'test';
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
p1.appendChild(document.createElement('br'));
p1.appendChild(document.createTextNode('newline displayed'));
Try
var p = document.createElement("p");
p.innerHTML = "Example Text<br>";
You can try this:
Give the table an id
Append html response to the table by using $('#tableid').html(responsedata);

Getting InnerHtml from a javascript Variable

I make an ajax call from my page , and then in response I also get some html like this
<parent id="1"><child></child></parent>
what I want is to get Inner HTML from the Response object excluding <parent>
How can I do that?
Cant use document.getElementbyID on a variable.
you can create a jQuery wrapper for the variable content and then extract the inner html using .html()
var data = '<parent id="1"><child></child></parent>'
var x = $(data).html()
Pure JS if you like ->
http://jsfiddle.net/eztZm/
//get
var get_html = document.getElementById("parent").innerHTML;
console.log(get_html);
//set
document.getElementById("parent").innerHTML = "new html";
https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
html code used:
<parent id="1"><child>candy</child></parent>
first approach:
var parent = document.getElementById("1");
var child_text = parent.firstChild.innerHTML;
to make a long story short:
document.getElementById("1").firstChild.innerHTML
will deliver "candy" (without jQuery) :)

Accessing a Dynamically Named array in jQuery/javascript

I wish to name an array according to the table row containing the button that was clicked.
I get the table row thus:
var rowNum = $(this).parent().parent().index();
Now, I wish to name the array and access it.
var arrayName = 'arrTR' + rowNum;
window[arrayName] = new Array();
window[arrayName]["First"] = "Bob";
window[arrayName]["Last"] = "Roberts";
window[arrayName]["email"] = "me#there.com";
//The array should be accessible as arrTR__
alert(arrTR1["Last"]);
The alert does not work, so I am doing something wrong.
How should I refactor the code to allow me to update and access the array?
jsFiddle
What you're doing with the dynamically named variables is essentially creating an array of those variables (one for each rowNum), but giving each of those array elements its own individual named variable.
There is a much better way to do this. Instead of generating a series of dynamically named variables, make a single array or an object. Then add an element or property for each of the dynamically named variables you were going to generate.
Your test code could look like this:
var arrTR = [];
var rowNum = 1;
arrTR[rowNum] = {
First: 'Bob',
Last: 'Roberts',
email: 'me#there.com'
};
alert( arrTR[1].Last );
Alternatively, you can do something with $.data as mentioned in Johan's answer. But if you do use plain JavaScript code, use a single array as described here instead of multiple dynamically named variables.
There are several reasons to do it this way. It's cleaner and easier to understand the code, it may be faster when there are large numbers of entries, and you don't have to pollute the global namespace at all. You can define the var arrTR = []; in any scope that's visible to the other code that uses it.
Arrays and objects are made for keeping track of lists of things, so use them.
There is nothing wrong with your code, and the only place it has error is the alert since it is not defined on the first click button
see this fiddle with a little update
if(rowNum === 1)
alert(arrTR1["Last"]);
else if(rowNum === 2)
alert(arrTR2["Last"]);
fiddle
How about something like this?
$('.getinfo').click(function() {
var result = $('table tr:gt(0)').map(function(k, v){
return {
firstName: $(v).find('.fname').val(),
lastName: $(v).find('.lname').val(),
email: $(v).find('.email').val(),
}
}).get();
//update to show how you use the jQuery cache:
//1. set the value (using the body tag in this example):
$('body').data({ result: result });
//2. fetch it somewhere else:
var res = $('body').data('result');
});
Not sure how you want to handle the first row. I skip in in this case. You can access each row by result[index].
As you might have noticed, this saves all rows for each click. If you want to use the clicked row only, use the this pointer.
http://jsfiddle.net/nwW4h/4/

JavaScript, numbers and strings

I need to automatically populate certain cells of a table according to the cell name (that as to be a number) but when you call the cell by it's name it gets interpreted as it's index number and instead of populating the correct cell it will populate the ordinal cell corresponding to the index.
document.getElementById("myTR").cells['9'].innerHTML = "testValue"
//the following doesn't work either
a ='9' or a = 9
b = a.toString()
document.getElementById("myTR").cells[b].innerHTML = "testValue"
Any ideas how to solve this?
I've tried to aggregate a letter to the number (9n) and it works, I just wonder if there is any know procedure for this.
document.getElementsByName('9')[0].innerHTML = 'testVal';
gets elements by name, selects the first (only) element and Bob's your uncle.
You may try this
HTML
<table>
<tr id="myTR">
<td>Row1</td><td name="9">Row1</td>
</tr>
<tr><td>Row2</td><td>Row2</td></tr>
</table>
JS
var x='9';
document.getElementsByName(x)[0].innerHTML = "testValue";
DEMO.
Also try to avoid to declare names that begins with numbers.
try this if the name is unique:
document.getElementByName('9').innerHTML = 'testValue';
by the way, I suggest u use jquery to operate the cell, follow is the code use jquery:
$('td[name=9]','#myTR').html("testValue");
Not sure if I will get frowned upon by JS purists, but I suggest using jQuery for this, this is what it was built for:
$("#myTR TD[name='9']").html("testValue");
This should get the cell named 9 in the tr tag with id myTR
Heres a fiddle for you: http://jsfiddle.net/aZEXV/1/

Categories