I need to display user input inside the div. But if the user put in tag, it will execute whatever inside the script tag.
For example
<html>
<body>
<button onclick="runTest('<script>alert(\'test\')</script>')">Click Me</button>
<div id="test"></div>
</body>
</html>
And my javascript runTest function
function runTest(str) {
$('#test').append($('<div>' + str + '</div>'));
}
If I run this, it will cause alert() to be executed. I tried to use escape(str), but it displays the escape characters %3Cscript%3Ealert%28%27test%27%29%3C/script%3E
Any idea? Here is the fiddler: https://jsfiddle.net/zvLg1w6q/1/
Thanks...
you can use this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
and use it same as follow:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')
<div id="myDiv">
</div>
Related
Is it possible to implement a counter which directly changes the text of a tag using jQuery/Javascript? For example if I had 2 tags:
<a>hello</a>
<a>bye</a>
After running the jQuery/JS function, this is what would happen:
<a>[1]hello</a>
<a>[2]bye</a>
I can't use a CSS counter as I need the script to directly edit the HTML.
You can use .html(function)
$("a").html(function(index, html) {
return "[" + (index + 1) + "]" + html;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
You could loop through all the anchors and add the index to the content using .prepend() :
$("a").each(function(index,value) {
$(this).prepend("["+(index++)+"] ");
})
Hope this helps.
$("a").each(function(index,value) {
$(this).prepend("["+(index++)+"] ");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
With pure JS, you can use create a text node and insert it as the first child node to get the counters - see a demo below:
Array.prototype.forEach.call(document.querySelectorAll("a"), function(e, i) {
e.insertBefore(document.createTextNode(`[${i+1}]`), e.childNodes[0]);
});
<a>hello</a>
<a>bye</a>
Use this code,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
<script>
$("a").html(function(index, data) {
return "[" + (index + 1) + "]" + data;
})
</script>
How to call the Method in Jquery's Append Method ?
I have the HTML code in which I use the append method() on click of a button.
I want to append the HTML with viewbag data using loop.
here is my code , is that right ?
<html>
<body>
<div class="row-fluid" id="MyCode">
</div>
<button name="AddCode"></button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function ()
{
$('#AddCode').click(function () {
$('#MyCode').append("<di ><div class='span2'>" +
//I want to call the function here...
AddDivs()
);
});
function AddDivs()
{
var ht="";
#foreach (var item in ViewBag.LocationList)
{
ht += "<div id='"+item.Id+"_"+item.Name+"'></div>";
}
}
});
</script>
Its showing undefined.
Change foreach loop with following:
#foreach (var item in ViewBag.LocationList)
{
// these lines are client codes that is in server codes
<text>ht += "<div id='" + #item.Id + "_" + #item.Name + "'></div>";</text>
}
if you dont write your js codes in <text>, razor assume that ht is an server variable.
script tag must be inside of body tag
<script type="text/javascript">
...
</script>
</body>
</html>
I am pulling in tweets through a getJSON and writing them to a Google map infowindow with javascript. The problem is, these tweets come with text links but no formatting (and no ids/classes/anything for which to narrow a find and replace). This is the mash of code I'm using right now to find the text, but I can't get it to wrap whatever it finds in <a> tags to properly display the links:
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
var jthis = $(this);
$("*").each(function () {
if (jthis.children().length == 0) {
jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
Did I overlook something or does anyone know a better way to do this?
If i understand your problem right, this should work.
not sure why you are iterating through elements as regexp will scan all the text anyway.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script>
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
$(".tweet").each( function(){
$(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap));
})
}
$(document).ready(replaceText);
</script>
</head>
<body>
<div class="tweet"> test 1 http://example.com/path </div>
<div class="tweet"> test 2 http://example.com/path </div>
</body>
</html>
I am using jscript to insert HTML.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;}
The HTML part of the variable is passed just fine, but the JQuery animations do not work. If I hard code this in the HTML like below the animations work fine.
<div id="pluginWidgets2Div">
<a id="OrderTotals" href="">Order Totals</a>
<p id="OrderTotalText">Hiya<br />
Such interesting text, eh?</p>
<a id="FreightView" href="">View Freight</a>
<p id="FreightViewText" style="display: none">Hiya<br />
Such interesting text, eh?</p>
Another (3)
Menu item 4
One more (5)
<script>
$("#OrderTotals").click(function () {
$("#OrderTotalText").toggle("fast");
});
$("#FreightView").click(function () {
$("#FreightViewText").toggle("fast");
});
</script></div>
Thanks for your help.
.innerHTML doesn't execute script elements. You can use .html() in jQuery ...
Or do the sensible thing which is just running that code directly:
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
$('#OrderTotals').click(function () {
$('#OrderTotalText').toggle('fast');
});
}
There's a nice unobtrusive way to have this code waiting in the wings so that it will work. When inserting the HTML, skip the JavaScript - handle it separately.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
}
$(document).ready(function(){
$("#pluginWidgets2Div").on("click", "#OrderTotals", function () {
$("#OrderTotalText").toggle("fast");
});
});
The jQuery will apply to the HTML if/when it's inserted, and your HTML doesn't need to have any JavaScript in it.
You haven't closed the <script> tag:
orderTotalsHTML = "<a id='OrderTotals' href='#'>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});</script>";
I am getting an $("<div/>").text(value).html is not a function error in the code below:
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).html(
'<div>' +
htmlEncode(imagefilename) +
'<button type="button" class="imageCancel" cancel_image_file_name="' +
imagefilename +
'">CANCEL</button></div>'
);
return true;
}
How can this error be fixed?
The strange thing is I have a similar code below but different function (stopImageUpload) and the code works fine below:
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function stopImageUpload(success, imagefilename) {
imagecounter++;
$('.listImage').eq(window.lastUploadImageIndex).append(
'<div>' +
htmlEncode(imagefilename) +
'<button type="button" class="deletefileimage" image_file_name="' +
imagefilename +
'">Remove</button><br/><hr/></div>'
);
return true;
}
Link to application to see what is happening is here: application
$('<div/>').html(value); //without text function
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
If value in the above snippet is undefined, then text() returns the DOM Element's text content, not the element itself, causing the chained call to fail.