jquery adding table row with commented out html - javascript

I have a table and I want to add a new row to this table. I load html of the row from the server. Returned html has some other commented out html on the top. Because of that comment adding row doesn't work properly. jQuery removes <tr> and <td> tags and adds plain text from <td> elements. Is it a bug or expected behaviour?
<table id="tbl">
<tr><td>old1</td></tr>
<!-- <abc -->
<tr><td>old2</td></tr>
</table>
<input id="add" type="button" value="add"/>
JavaScript:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>");
});
fiddle
P.S. The issue is because of '<' in the comment. It works ok with normal comments. And it would also work with '<' if the comment was inserted into/from div elements rather than table/tr. What would be your suggestion to fix this issue without removing comment from the html on server-side.

You can simply remove comments by using regular expressions. Code(Demo on JSFiddle):
$("#add").click(function() {
var rawHTML = "<!-- <abc --><tr><td>New</td></tr>";
var HTMLToAdd = rawHTML.replace(/<!--[\s\S]*?-->/g, '');
$("#tbl tr:last").after(HTMLToAdd);
});
Shorter version:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>".replace(/<!--[\s\S]*?-->/g, ''));
});

Referring to my comment above - e.g. the below JS works...
$("#add").click(function() {
newRow = '<!-- <abc --><tr><td>New</td></tr>';
var newRow = newRow.replace('<!-- <', '<!-- ');
$("#tbl tr:last").after(newRow);
});
where the newRow is actually the data returned by your server call.

if you get always string like that and you don't want to have comment at all, you can strip it off
$("#add").click(function() {
var responseString = "<!-- <abc --><tr><td>New</td></tr>";
var index = responseString.indexOf("-->")+3;
var formatedString = responseString.slice(index);
$("#tbl tr:last").after(formatedString);
});

Related

Cannot append to node

I have a the following html code in a table:
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
When I click the button, I would like to empty the td and add the text which is stored in a cookie. The td empties fine but I am unable to append the text. The text is in the variable as it is visible in the alert. I have used the code below to try and achive this, the commented out code is what I have tried and doesn't work.
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
//alert(hostname);
var trid = $(this).closest('tr').attr('id');
//alert(trid);
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
$(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').append(olddesc);
// $(this).closest('tr').find('#description').text(olddesc);
// $(this).closest('td').text(olddesc);
// $('#'+trid+' td').each(function(){
// if($(this).attr('id') == 'description'){
// $(this).append(olddesc);
// }
// })
//$(document).find('#'+trid+' td#description').append(olddesc);
})
Can anyone please help me fix this or recommend a better way of doing it?
You can use .html() to add your dynamic data to HTML tag id
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
// Create custom / dynamic HTML
var temp = `<p>` + olddesc + `</p>`;
$(this).closest('td').empty(); <----- THIS WORKS
// Edit: Use ID of html tag
$('#description').html(temp);
This shall work for you.
$(this).closest('td').append(olddesc); runs after you've removed this from the td, therefore the td is no longer an ancestor of this. You do not need to empty the td; simply set its text to olddesc and it will be automagically emptied as part of the process of setting its text.
// (REMOVE THIS) $(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').text(olddesc);
Just use .html
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
var olddesc = "Cokkies return"; //Cookies.get(hostname+','+trid+',description');
$(this).closest('td').html(olddesc); //<----- THIS WORKS
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
</tr>
</table>

Prevent html tag creation during html() using Jquery

I am having a string "<F1>" and whenever I add it as html to a particular div using jquery's html(), as
var str = "<F1>";
$("div").html(str);
It generates html for div as
"<f1></f1>"
But I dont want such tag creation.
I need to have div with html as
"<F1>"
It will be appreciated if somebody guide me, to achieve this. :(
Use .text() instead of .html().
var str = "<F1>";
$("div").text(str);
Fiddle: http://jsfiddle.net/6942a/
To escape the HTML entities in str and use .html() you can do the following:
var str = "<F1>";
str = $("<div/>").text(str).html();
$("div").html(str);
Updated jsfiddle: http://jsfiddle.net/6942a/3/
Use this :
HTML:
<div></div>
<input type="text">
<input type="button" value="ADD">
jQuery :
$(function(){
$('input[type=button]').click(function(){
var text = $('input[type=text]').val();
text =text.replace('<','&#60');
text =text.replace('>','&#62');
$("div").html(text);
});
});
Demo
For more information see html entities
Try this
var str = '<f1>';
var res = str.replace("<", "<");
res=res.replace(">", ">");
$("div").text(res);
Fiddle

Dynamically appending a row by cloning an existing row?

I have a row in a table and that row is not displayed as css style is set to display:none .
HTML table:
<table class="myTable">
<tr class="prototype">
........
</tr>
</table>
CSS code:
.myTable .prototype{display:none;}
Now i have to clone the same row and add some data to it and append the row to the table as below: i have below jquery code:
var master = $(this).parents("table.myTable");
var prot = master.find(".prototype").clone();
prot.attr("class", "");
prot.find("#attributeValue").attr("value", "ABC");
prot.find("#contactFirstName").attr("value", "XYZ");
jQuery('table.myTable tr:last').before(prot);
But the row won'ttbe added to the table. Please help me.
Thanks!
If you run the code in the onLoad event, change the first line to var master = $(this).find("table.myTable"); or var master = $("table.myTable");
Use prot.removeClass(); instead of prot.attr("class", "");
Ids have to be unique, if elements in your prototype-row have an id you get invalid HTML.
Use $().val('ABC') instead of $().attr('value', 'ABC')
If it still doesn't work, please show more code (maybe a jsfiddle).
var master = $(this).parents("table.myTable");
var prot = master.find("tr.prototype").clone();
prot.removeClass('prototype');
prot.find("#attributeValue").val("ABC");
prot.find("#contactFirstName").val("XYZ");
master.append(prot);
prot.show();

Update anchor using JavaScript

I have a page with a table. The table contains th elements, which contain anchors. This is what an example th looks like:
<th scope="col">
Inventory reference
</th>
What I want to do is update the anchor so that it has an extra query string parameter thus:
<th scope="col">
Inventory reference
</th>
Now, I now that I must do this:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('th[scope^=col]') ???
})
</script>
The problem is though, that I don't know what should replace ???. Does anyone have any idea? I'm thinking I need some JavaScript or JQuery code that grabs the anchor and then appends the extra query string parameter. Question is what exactly should the code be?
Thanks,
Sachin
Try this:
$(document).ready(function(){
$('th[scope^=col]').each(function(){
var old_link = "";
var new_link = "";
//Get the current href value of the child anchor tag of 'th[scope^=col]'
old_link = $(this).children('a').attr('href');
//Append the extra string required '(in this case &page=3)' to the old_link
new_link = old_link + '&page=3';
//Set the href value for the anchor tag within 'th[scope^=col]'
$(this).children('a').attr('href',new_link);
});
});
Hope this helps.
Try this
$(document).ready(function () {
$('th[scope=col] a')[0].href += "&page=3";
});
If you think the url can already contain page param in the querystring and you just have to update its value then use this code.
$(document).ready(function () {
$a[0].href = $a[0].href.replace(/([?&])page=[^&]*&?/,'$1') + '&page=3';
});
$(document).ready(function () {
$('th[scope=col] a').each(function(){
$this = $(this);
$this.attr('href', $this.attr('href') + '&page=3');
});
});

How to write a table content to an xml?

Can somebody tell me how can i write a clientside table control content to an xml on a button click . I'm using a clientside table "selectedTexts" and on save button click i need to save the table content to an xml. Please help.
$(document).ready(function() {
$('#<%=btnSave.ClientID %>').click(function(event) {
var xml = "<schedule>";
$("#selectedColumns").find("tr").each(function() {
xml += "<data>";
xml += $(this).find("td").eq(1).html() + "\n";
xml += "</data>";
});
xml += "</schedule>";
this.isPrototypeOf(
alert(xml);
})
});
I managed to get the string in an xml format. How can i pass this string to my codebehind so that i can write it to an xml file. Or is it any other methods available to write it from the clientside itself?
if your table's code is as follows:
<table id="root">
<tr id="category_1">
<td>value-1</td>
<td>value-2</td>
</tr>
<tr id="category_2">
<td>value-7</td>
<td>value-8</td>
</tr>
</table>
then following JQuery will convert it to a xml where comments wih // denote first time output:
var xml="";
$("#root").each( function(index){
xml +="<"+$(this).attr("id")+">";
// <root>
$("#root tr").each( function(index){
xml +="<"+$(this).attr("id")+">";
// <root><category_1>
$(td,this).each( function(index){
xml +="<"+$(this).html()+">";
// <root><category_1><value_1><value_2>
}
}
}
Should work :-) ta-da...
#NewBie: I assume you are unable to generate id for <tr> so I am suggesting this way:
As you see in the code I have written: $("#root tr").each( function(index){
Here, index is the loop variable to represent current node/count of the matched element. For example if you had 50 <tr> row then index starts with 1 and goes upto 50. Thus you can use this variable to mark your <tr> tag :-)
Just edit like this:
$("#root tr").each( function(index){
xml +="<"+index+">"; // replaced $(this).attr("id") with index
// other codes here
}
Best of luck...

Categories

Resources