Javascript - Slashes are replaced by spaces - javascript

I am trying to create an li element in my html code via javascript. This li will have an onclick function. The problem is that trying to pass a file path as an argument in the loadDoc2() function, some problems occur. I am including the code.
function myFunction(){
var x = "NEW";
var file = "'/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml'";
lis = "<li><a onclick='loadXMLDoc2(" + file + ")'>" + x + "</a></li>";
document.getElementById("demo").innerHTML = lis;
}
This gives me <a onclick="loadXMLDoc2(" static brands perla new col xml files new col.xml')'>NEW</a>. The slashes are replaced by spaces and letters are low case. The result that I need is <a onclick="loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')">NEW</a>
I have tried many things such as .replace("\", "//") but it didn't work.

This happens because you start your onclick with ' and file has a ' at the start, so it closes the onclick attribute. So it looks like
<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')'>NEW</a></li>
I suggest you use javascript to bind the event, it's gonna be way easier.
function myFunction(){
var x = "NEW";
var file = "/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml";
var li = document.createElement('li');
var a = document.createElement('a');
a.innerHTML = x;
a.onclick = function(){
loadXMLDoc2(file);
}
li.appendChild(a);
document.getElementById("demo").appendChild(li);
}

<div id="container"></div>
<script>
var container = document.getElementById('container');
var li = document.createElement('li');
li.innerText = "Im a list item";
li.onclick = function(){
console.log('I was clicked');
}
container.appendChild(li);
</script>

you appear to have conflicting quotes.
lis === "<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml')'>NEW</a></li>"
note that k='loadXMLDoc2('/ will open then close the quotes. fixed by changing single to double quotes:
var x = "NEW";
var file = "'/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml'";
lis = `<li><a onclick="loadXMLDoc2(${file})">${x}</a></li>`;
document.body.innerHTML = lis;

Related

How to change the indentation of new added script tag content

i'm using the following code to insert new script with content to HTML file,
Currently the following code is working and the new script is inserted after the first existing script, the problem is the content is not indent
e.g. this is the output of the new added script(as you can see its in one line)
<script> var keyOfFilesArray = Object.keys(data)[0]; var filesArray = data[keyOfFilesArray]; </script>
I want to change it to be indented like following:
the second added open script tag will be inserted line after the closing tag of the first script
the vars should be inserted one after other to be like this
<script>
var keyOfFilesArray = Object.keys(data)[0];
var filesArray = data[keyOfFilesArray];
</script>
How I can do that ? I belive I need to add the /n but not sure where is the best way to insert it...
https://jsfiddle.net/k32ntkr8/
This is the JS code
btn.onclick = function(e){
debugger;
var innerhtml = [
' var keyOfFilesArray = Object.keys(data)[0];',
' var filesArray = data[keyOfFilesArray]; '
].join('');
var html = process(input.defaultValue,innerhtml);
output.value = html;
}
function process(html,innerhtml) {
var escapedHTML = html
.replace(/body/g, 'body$')
.replace(/head/g, 'head$');
sandbox.innerHTML = escapedHTML;
var script = sandbox.querySelectorAll('#app-ux-bootstrap')[0];
var newScript = document.createElement('script');
newScript.innerText = innerhtml;
script.parentNode.insertBefore(newScript, script.nextSibling);
var unescapedHTML = sandbox.innerHTML
.replace(/body\$/g, 'body')
.replace(/head\$/g, 'head')
.replace(/"/g, "'");
return (
'<!DOCTYPE HTML>\n<html>' +
unescapedHTML +
'</html>'
);
};
How it can be done? please suggest ,the answer below doesn't help much...
if I can improve this question somehow please let me know.
Something like this?
var innerhtml = [
'\tvar keyOfFilesArray = Object.keys(data)[0];',
'\tvar filesArray = data[keyOfFilesArray];'
].join("\n");
var script_code = '<script>\n' + innerhtml + '\n<\/script>';
Then just insert the script_code variable wherever you want it to appear on the page.
https://jsfiddle.net/e72c17zg/1/
Ok, if you change your onclick handler to this
btn.onclick = function(e){
debugger;
var innerhtml = [
'',
' <script>',
' var keyOfFilesArray = Object.keys(data)[0];',
' var filesArray = data[keyOfFilesArray]; ',
' <\/script>'
].join('\n');
var html = process(input.defaultValue,innerhtml);
output.value = html;
}
And change the lines of process that populate the script to this
var script = sandbox.querySelectorAll('#app-ux-bootstrap')[0];
script.parentNode.insertAdjacentHTML('afterBegin', innerhtml);
You should get this output
<head>
<script>
var keyOfFilesArray = Object.keys(data)[0];
var filesArray = data[keyOfFilesArray];
</script>
...
</head>

How to add a JavaScript function to an HmlGenericControl from codebehind

From server side, I'm injecting an input and button element dynamically to client side. I also would like to inject a JavaScript function into each. The input's function should be triggered onchange and for the button's, should be onclick
This is what I've done so far:
//js definition
string script = #"<script>";
script += #" function OnCroquis0BtnClick()
{
var fileUp = $('#File');
fileUp.trigger('click');
}";
script += #"function OnCroquis0FileSelected()
{
txtBx = document.getElementById('MainContent_txtBx');
var fileUpload = document.getElementById('File');
txtBx.value = fileUpload.files[0].name;
}";
script += #"</script>";
ClientScript.RegisterClientScriptBlock(GetType(), "testScript0" ,
script);
//html elemets definition
HtmlGenericControl input = new HtmlGenericControl(),
btn = new HtmlGenericControl();
input.TagName = "input";
input.ID = lbl.Text + "File";
input.Attributes["onchange"] = "OnCroquis0Fileselected()";
input.Attributes["style"] = "display: none;";
docRequeridosMainDiv.Controls.Add(input);
btn.TagName = "button";
btn.ID = "btn";
btn.InnerText = "Anejar";
btn.Attributes["onclick"] = "OnCroquis0BtnClick(); return false";
btn.Attributes["style"] = "margin-right:2%;";
docRequeridosMainDiv.Controls.Add(btn);
They are visible and style's are being applied, but js isn't. I figured since any html attribute is added through Attributes["attri"] maybe a js function could be too.
Thanks, in advance.
Try using RegisterStartupScript instead of RegisterClientScriptBlock
Page.ClientScript.RegisterStartupScript(this.GetType(), "testscript0", script, false);
this enforces that script is executed after all the elements in the page gets loaded.
Managed to get it working. On my version, I had function names misplaced :P

Simple ToDo-List doesn't work

My ToDo List dont wanna work the way i want. I've just been working with JavaScript for 2 weeks sthis is very new to me, therefor the code maybe doesnt look that nice.
The result comes out wrong. If I type in "buy food" the first line gonna show just that, but the next time I wanna add "walk the dog", then it displays
buy food
buy food
walk the dog
I hope you understand my problem. It also ends the unordered list tag after the first click and adds the rest of the things in another.
Here's the JavaScript:
var taskList = [];
var text = "<ul>"
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The issue is you're closing the ul tag after adding each item. Instead of concatenating raw HTML, consider using element objects and appending, and using a text node object to handle the user input - this removes the possibility of a DOM Based XSS vulnerability.
window.onload = function() {
var taskList = [];
var container = document.getElementById("todoList");
document.getElementById("add").onclick = addToList;
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
var ul = document.createElement('ul');
var li;
for (i = 0; i < taskList.length; i++) {
li = document.createElement('li');
li.appendChild(document.createTextNode(taskList[i]))
ul.appendChild(li);
}
container.innerHTML = '';
container.appendChild(ul);
}
};
Task:
<input id="toDoTask" /> <input type="button" id="add" value="Add" />
<div id="todoList">
</div>
You should not use the innerHtml. This replace all the text of your content. You should just add the li to your ul.
You can do that by using the append function by jquery Append
your <ul> must contain an id like this <ul id="toDoList">
then you make $("#toDoList").append("yourTask");
yourTask must contains the li.
With this, you don't need to iterate on all your element list
Not sure, but you seem to keep adding to text the second time, so text will be something like <ul><li>buy food</li></ul><li>buy food</li><li>walk the dog</li></ul>, which is invalid HTML by the way, but gets outputted anyway...
On each call of function addToList() you should reset the variable text.
For example:
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
text="";
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The whole list of items in array will appends to variable text on each call.

Cant find Element

So I want to write out the text inside input value item and make a another node to right of the text. But this text just shows [object HTMLParagraphElement] next to the text in the input, why doesnt it shows the text?
I dont know what I do wrong, please help me!
so the text from the input is showed but not the other p element I made?
Here is the code:
var lista = document.getElementById("lista");
var li = document.createElement("li");
var del = document.createElement("p");
var delt = document.createTextNode("remove this");
del.appendChild(delt);
var item = document.getElementById("item");
var text = document.createTextNode(item.value + " | " + del);
li.appendChild(text);
lista.appendChild(li);
You don't need to create text nodes to append the text. Just set the innerHTML on the elements you are creating:
var myPar = document.createElement('p');
myPar.innerHTML = "remove this";
li.innerHTML = myPar.outerHTML; //this would be the tag and its text <p>remove this</p>
// other code here.
Demo Fiddle
the problem is the line
var text = document.createTextNode(item.value + " | " + del);
at this time ,the 'del' referenced a paragraph element,
you could have "del.innerHtml" instead of 'del'
Change your code to use del.innerHTML.
var text = document.createTextNode(item.value + " | " + del.innerHTML);
the argument of document.createTextNode must be a string.And the innerHTML is the html code of a element object.
http://jsfiddle.net/4YgXG/
HTML:
<ul id="lista"></ul>
Js:
// EXAMPLE!
var lista = document.getElementById("lista");
var item = document.getElementById("item");
for(var i=0;i<100;i++){
var li = document.createElement("li");
var del = document.createElement("p");
del.innerHTML = 'Remove this';
li.appendChild( del );
lista.appendChild(li);
}

regular expression replace with prototype?

I got some html formatted in the following way:
[Title|<a class="external" href="http://test.com">http://test.com</a>]
From these texts I'd like to create links using "Title" as the text and "http://test.com" as link. How can I best do this in prototype?
Pure RegExp:
var ProperLink=WierdString.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/,'$2$1</a>')
in the context you provided:
function convert(id){
$(id).innerHTML=$(id).innerHTML.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/g,'$2$1</a>');
}
convert('testdiv');
Here is a regex that will retain the original attributes of the anchor tag while doing the replacement:
var link = "[Title|<a class=\"external\" href=\"http://test.com\">http://test.com</a>]";
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/;
link.replace(pattern, "$2$1$3"));
The output is:
<a class="external" href="http://test.com">Title</a>
Without prototype: http://jsfiddle.net/JFC72/ , you can use prototype to make it simpler.
var myStr = "[THIS IS TITLE|http://test.com]";
document.getElementById('testdiv').innerHTML = getLink(myStr);
function getLink(myStr)
{
var splitted = myStr.split("|http");
var title = splitted[0].substring(1);
var href = splitted[1].substring(0,splitted[1].length-1);
return "<a href='http" + href + "'>" + title + "</a>";
}
var dummyDiv = document.createElement('div');
dummyDiv.innerHTML = '[Title|<a class="external ...';
var parts = dummyDiv.innerText.slice(1, -1).split('|');
// parts[0] is the text, parts[1] is the URL

Categories