How to add something in html string - javascript

How I can add something in html string with jquery.
String html :
var stringHtml = '<td>Column 1</td><td>Column 2</td><td></td>';
I want add something in last td ( td:eq(2) ), and then append it to table.
I try:-
var stringHtml = '<td>Column 1</td><td>Column 2</td><td></td>';
$(stringHtml).find('td:last').append('<button>MyButton</button>');
$('#myTable tbody').append(stringHtml);
This script not working.
Thank you for helping.

You are appending the string, not the jQuery object.
var $ele = $('<td>Column 1</td><td>Column 2</td><td></td>');
$ele.find('td:last').append('<button>MyButton</button>');
$('#myTable tbody').append($ele);
// or $ele.appendTo('#myTable tbody');
UPDATE : The same behavior with one linear code using chaining.
$('<td>Column 1</td><td>Column 2</td><td></td>').appendTo('#myTable tbody').find('td:last').append('<button>MyButton</button>');

Related

How can I add data params to an HTML string and get a string back?

I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

Duplicate a specific html code in jquery

I have a table with some complicated values (I mean I have to make several requests to get all the values that I want in it). I need to add rows at the end of this table and fill the cells with the same code as the existing html code.
For example, I have something like :
<table id="table_cultures">
<tr>
<td>Just a string</td>
<td>Dropdown</td>
<td><div class='foo'> something..</div></td>
</tr>
</table>
<button id="plus_button" onclick="addRow()">+</button>
Now, in my javascript, I have something like :
function addRow(){
var table = document.getElementById("table_cultures"); //Get the table element
var itk = document.getElementById('foo'); //Try to get the html to duplicate
var row = table.insertRow(-1); //Add in the end of the table
var c1 = row.insertCell(0);
var c2 = row.insertCell(1);
var c3 = row.insertCell(2);
c1.innerHTML= 'Culture';
c2.innerHTML='test';
c3.innerHTML=itk;
}
So, in the variable itk, I'm trying to get the html generated and pull it into the cell, bu[Object]t it displays just HTMLFormElement (because it's a table that I want to duplicate).
Is that possible to do it that way ? Or there is an other way more simple please ?
You shall consider cloning the row node instead of getting and setting innerHTML with some thing like this:
var table = document.getElementById("table_cultures"); //Get the table element
var row = document.getElementById("rowTobeCloned"); //clone the required row
var clone = row.cloneNode(true); // copy child nodes too
table.appendChild(clone); // append the new row to the end of the table
At the moment you are not using jQuery in your code at all, but if you are looking for a jQuery solution you should try .clone()
$("#table_cultures td:last").clone().appendTo("#table_cultures tr");
JSFiddle
You using class("class='foo'") not Id ("getElementById")
so it should be something like this
function addRow(){...
var itk = document.getElementsByClassName('foo')[0]; //Try to get the html to duplicate
...}

How to add text between html tags in a string client side?

After a call in a library I get the following string
var data = "<td>123.456</td>";
I'd like to insert some data (a <img /> tag) after the content of the <td></td> and get something like
<td>123.456 <img src='path' /></td>
How to properly do this in JQuery ?
You can use convert your variable in jQuery object the use append() to append img
var data = "<td>123.456</td>";
data = $(data).append("<img src='path' />").prop('outerHTML');
alert(data)
DEMO
You can append the data you want using :
$('td').append('<img src="path">');
Working Demo : JsFiddle
You can do like this :
var imagevalue = '<img src="path">';
var data = "<td>123.456 "+imagevalue+"</td>";
If you want to get the modified string in a variable
var string = '<td>123.456</td>';
//create a temp element with the contents of the given string
var $div = $('<div />', {
html: string
});
//find the td and manipulate it
$div.find('td').append('<img src="path">');
//get the modified content from the temp element
var string2 = $div.html();
console.log(string2)
Demo: Fiddle
You could use jQuery for that, but it's easier to just use string operations in plain Javascript:
var data = "<td>123.456</td>";
data = data.replace("</td>", " <img src='path' /></td>");
Check the demo http://jsfiddle.net/yeyene/xQh5J/183/
Jquery
$(document).ready(function(){
var data = "<td>123.456</td>";
$('#my_table tr').append(data);
$('#add').on('click',function(){
$('#my_table td').html($('td').text()+' <img src="http://www.softicons.com/assets/templates/softicons/images4/winlogo.png" width="16" height="16" />');
});
});

img SRC from first cell in a row with jquery

i have a table such that each row is like this
<tr>
<td><input/> <img id="foo" src="redMinus.png"/></td>
some more tds
<td> <a onclick="wow('foo',$(this))"></a>
</tr>
I want to find out if the img in the first td has an src that contains "redMinus"
This is what I have but it doesnt seem to be working?
function wow(id, item){
var tr$ = item.parentNode.parentNode;
var details = tr$.find('img[src*="redMinus"]');
}
Any ideas?
Thanks!
You're mixing jQuery with DOM elements.
Change your code to
var details = item.closest("tr").find('img[src*="redMinus"]');
Your parameter is given the name item within your function, but you are trying to use a variable with the name item$ instead. Either rename the parameter or use the correct parameter name in the function.
var same = "redMinus" == $(this).parent('td').prev().children('img').attr('src').substring(0,7);
function wow(id, item){
var src = $('#' + id).attr('src');
var srcIndex = src.indexOf('redMinus');
if(srcIndex >= 0)
// redMinus is present in the string
else
// redMinus is not present in the string
}

what's the easiest method to append a TR to a table by javascript?

If the table id is known – so the table can be obtained with docoument.getElementById(table_id) – how can I append a TR element to that table in the easiest way?
The TR is as follows:
<tr><td><span>something here..</span></td></tr>
The first uses DOM methods, and the second uses the non-standard but widely supprted innerHTML
var tr = document.createElement("tr");
var td = document.createElement("td");
var span = document.createElement("span");
var text = document.createTextNode("something here..");
span.appendChild(text);
td.appendChild(span);
tr.appendChild(td);
tbody.appendChild(tr);
OR
tbody.innerHTML += "<tr><td><span>something here..</span></td></tr>"
The most straightforward, standards compliant and library-independent method to insert a table row is using the insertRow method of the table object.
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
P.S. Works in IE6 too, though it may have some quirks at times.
Using jQuery:
$('#table_id > tbody').append('<tr><td><span>something here..</span></td></tr>');
I know some may cringe at the mention of jQuery. Including a framework to do just this one thing is probably overkill. but I rarely find that I only need to do "just one thing" with javascript. The hand-coded solution is to create each of the elements required, then add them in the proper sequence (from inner to outer) to the other elements, then finally add the new row to the table.
If you're not opposed to using jQuery, you can use either of the following where "tblId" is the id of your table and "_html" is a string representation of your table row:
$(_html).insertAfter("#tblId tr:last");
or
$("#tblId tr:last").after(_html);
i use this function to append a bunch of rows into a table. its about 100% faster then jquery for large chunks of data. the only downside is that if your rows have script tags inside of them, the scripts wont be executed on load in IE
function appendRows(node, html){
var temp = document.createElement("div");
var tbody = node.parentNode;
var nextSib = node.nextSibling;
temp.innerHTML = "<table><tbody>"+html;
var rows = temp.firstChild.firstChild.childNodes;
while(rows.length){
tbody.insertBefore(rows[0], nextSib);
}
}
where node is the row to append after, and html is the rows to append
Really simple example:
<html>
<table id = 'test'>
<tr><td>Thanks tvanfosson!</td></tr>
</table>
</html>
<script type="text/javascript" charset="utf-8">
var table = document.getElementById('test');
table.innerHTML += '<tr><td><span>something here..</span></td></tr>';
</script>
I use this, works softly:
var changeInnerHTMLOfMyCuteTbodyById = function (id_tbody, inner_html)
{
//preparing
var my_tbody = document.getElementById (id_tbody);
var my_table = my_tbody.parentNode;
my_table.removeChild (my_tbody);
//creating dom tree
var html = '<table style=\'display:none;\'><tbody id='+ id_tbody+'>' +
inner_html + '</tbody></table>';
var tmp_div = document.createElement ('div');
tmp_div.innerHTML = html;
document.body.appendChild (tmp_div);
//moving the tbody
my_table.appendChild (document.getElementById (id_tbody));
}
You can do this:
changeInnerHTMLOfMyCuteTbodyById('id_tbody', document.getElementById ('id_tbody').innerHTML + '<tr> ... </tr>');

Categories