For starters, I have absolute no knowledge with javascript. I am trying to display a background image extracted from a url address on just a page of the questionnaire on qualtrics with the following codes:-
Qualtrics.SurveyEngine.addOnload(function()
{
<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src="http://webneel.com/wallpaper/sites/default/files/images/01-2014/2-flower-wallpaper.jpg" />
var string = 'http://webneel.com/wallpaper/sites/default/files/images/01-2014/2-flower-wallpaper.jpg';
document.getElementById("divtest").style.backgroundImage = "url('" + string + "')";
document.getElementById("imgtest").src = string;
});
But I got the following error message:-
Invalid JavaScript! You cannot save until you fix all errors: Unexpected token <
How do I go about fixing this?
You cannot add HTML directly in javascript code, you have to create into body section of your page, or if you need to create elements via code you have to use createElement
var _div = document.createElement('div');
_div.id = 'divtest';
_div.innerHTML = 'Hello';
_div.style.backgroundImage = "url('" + string + "')";
document.getElementsByTagName('body')[0].appendChild(_div); // to place as child of body
or
document.getElementById('[ID of parent element]').appendChild(_div); // to place as child of other element.
Related
Overview:
I am creating a web page using Python and generating both html as well as javascript in my code. Additionally, I am parsing through csv files and converting their table data to html. I want to be able to click on a line of text and the associated table data for that text would then be loaded into an iframe on the currently active web page. The problem I am having, is that my javascript function is not recognizing the key I send it to retrieve the corresponding table data. If I manually enter the key to return the table data, the correct data is returned - though the table doesn't load. However, if I generate the key programmatically, it returns as 'undefined' even though the strings appear to be identical.
Goal:
I need to figure out if there is something wrong with either the syntax, or the format of the key I am using to try and retrieve the table data. Secondly, I need to figure out why the table data is not being correctly loaded into my iframe.
Example:
import pandas
opening_html = """<!DOCTYPE html><h1> Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe name="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """ test-1<br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
java += """function send_table_data(obj) {
var t = obj.text + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementsByName('table_frame').src = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
EDIT: I did just figure out that for some reason there was a default space at the beginning of the var t - so using trim() seemed to fix that. Now, the only issue left is why the data doesn't load into the table.
It looks like you figured out your typo with the space that was messing with your key, so this is for your second question.
Your code
So to get your table to populate in the iframe you need to fix three things:
To edit the HTML contents of your iframe you should be setting the .srcdoc element, not .src
The document.getElementsByName() function will return an array of HTML elements so in order to get the element you want you should do one of the following:
(recommended) switch to using document.getElementById and use id='table_frame' in your iframe tags
select the first element of the array by using document.getElementsByName('table_frame')[0]
The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. A simple solution to this is to switch to using a <button> element in place of <a>.
Here is what your code looks like with the fixes:
import pandas
import json
opening_html = """<!DOCTYPE html><h1>Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe id="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<button href='' onclick="send_table_data(this);"> test-1</button><br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
#for the button, innerText needs to be used to get the button text
java += """function send_table_data(obj) {
var t = obj.innerText + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementById('table_frame').srcdoc = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
Other Recommendations
I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask, or a library that can assist in generating HTML using Python. (I would recommend Dash for your current use case)
I want to insert a javascript into a page whenever a site loads using Browser Helper object in IE-11.
public void OnDocumentComplete(object pDisp, ref object URL)
{
HTMLDocument document = (HTMLDocument)webBrowser.Document;
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)
document.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject =
(IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = "\nfunction hidediv(){document.getElementById" +
"('myOwnUniqueId12345').style.visibility = 'hidden';}\n\n";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
string div = "<div id=\"myOwnUniqueId12345\" style=\"position:" +
"fixed;bottom:0px;right:0px;z-index:9999;width=300px;" +
"height=150px;\"> <div style=\"position:relative;" +
"float:right;font-size:9px;\"><a " +
"href=\"javascript:hidediv();\">close</a></div>" +
"My content goes here ...</div>";
document.body.insertAdjacentHTML("afterBegin", div);
}
I want to get a javascript file inserted into page instead of using scriptObject.text.
I have a json response
Indicator:true
content:"Click here to open your message"
I need to convert the value of content to link. Right now it is in string. how to make it a href the actual link
Unfortunately the below code isn't working
let content = res.content
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div>'+content+'</div>';
var div2 = wrapper.firstChild;
You can use dangerouslySetInnerHTML to directly render HTML code in React.
createMarkup(content) {
return {__html: content};
}
convertFn(content) {
return <div dangerouslySetInnerHTML={createMarkup(content)} />;
}
getLink(){
... get json response ...
let content = res.content;
let linkContent = this.convertFn(content);
}
Edit: This is a React.js specific example.
The reason is the quotation symbols. your string ends at target.
You should put the somelink and the _blank inside quotation marks different from what you put the entire content in
ex:
content=''
or
content="<a href='somelink' target='_blank'></a>"
EDIT:
some people have misunderstood me as to saying its because he didn't put quotes outside of somelink.
its not that.
look at target. why is _blank black while the rest of content is reddish?
It's the type of quotes used that matter here.
use dangerouslySetInnerHtml prop to convert any html stored inside string into actual html markup.
for e.g.
htmlToText(content) {
return {__html: content};
}
render() {
return (
<div dangerouslySetInnertml={this.htmlToText(yourHtmlString)} />
)
}
or can be escaped
content = "Click here to open your message"
please install Prettier for editor help.
I find your code pretty working, As in the following snippet.
let content = 'Click here to open your message';
var wrapper = document.createElement('div');
wrapper.innerHTML = '<div>' + content + '</div>'; //No need to put in div
let div2 = wrapper.firstChild;
let a = div2.firstChild;
console.log(a.innerText)
console.log(a.getAttribute('href'), a.getAttribute('target'));
I wish to insert a variable that contains an HTML code in a DATA attribute (a href ... data-content= ...) it not work very well because the code inserted deletes some characters and suddenly it does not display properly.
Here is the code used
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('<i class="fa fa-file-o"></i> Aperçu');
}
AND my HTML output return this :
"><i class="fa fa-file-o"></i> Aperçu
Why it doesn't work ? What should I do?
Thank You
The problem with your code is there is special characters in the preview value . If you use code given below then you can override the problem and this is not the proper way and avoid this kind of coding style.Use data attributes for integers,small string values etc.. contents like html or long string values etc either use public properties or hidden controls.
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('</i> Aperçu');
$(".preview").data("content",preview);
}
well, lets fix this for the first: you have double quotes in the preview var you should escape them with '\' e.g.:
var preview = '<img src=\"' + url + '\" width=\"250\">';
or better use single quotes inside the var
var preview = "<img src='" + url + "' width='250'>";
but I think it's not good approach to store html in this attr - would be better to store here url only and html in the separate template. or render the hidden element on page load
I've looked at many other posts and I think I'm using the exact syntax suggested. However, I'm not getting the images to show up. I have a jsfiddle. Is it a jsfiddle issue? It's also not working on a website I'm working on.
<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src="http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg" />
var string = "url('http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;
Two minor problems:
getElementByID is not a function; getElementById is.
The format for a url is different for an image source and a background image. Try this:
var string = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg';
document.getElementById("divtest").style.backgroundImage = "url('" + string + "')";
document.getElementById("imgtest").src = string;
Replace getElementByID by getElementById and there is another error in your code:
you write:
var string = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";
document.getElementById("imgtest").src = string;
But src doesn't need url(, so you should write :
var str1 = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";
document.getElementById("divtest").style.backgroundImage = str1 ;
var str2 = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg';
document.getElementById("imgtest").src = str2;
Hope this helps