JavaScript: string use in dynamic HTML - javascript

I'm new to JavaScript and have an issue with passing a string to 'innerHTML' as part of the dynamic creation of an HTML document. Reason for this: I need to specify an image path and want to be able to output a different image onto the screen depending on the details retrieved from a cookie (i.e. the image path changes each time so that image = 1001.jpg, image = 1002.jpg etc, depending on the object details retrieved). At present, unless I hardcode the line:
"<p><img src=\images/1005.jpg"\"</p>";
I don't get an output. I tried various ways of inputting a string into this line but no joy so far. My code is probably not the best, but it works, apart from the image issue:
function changeMe(){
...
var studentObject = JSON.parse(getName); // info from cookie
var path = studentObject.imagePath; // works: images/1005.jpg
var res = path.charAt(10)
//alert(res); // = 5, works
var newPath = "<p><img src=\"images/1001.jpg\"></p>";
// I 'amend' the newPath string value:
**var answer = newPath.substr(0, 23) + res + newPath.substr(25.26);**
//alert(answer); // works: <p><img src=\"images/1005.jpg"\</p>
var oPara = document.createElement('p');
oPara.style.fontFamily = "Arial sans-serif";
oPara.style.fontSize = "20px";
oPara.style.color = "#77787E";
oPara.style.fontWeight = "bold";
oPara.innerHTML = "<p><br>Name & Surname: " + studentObject.name + " " +
studentObject.surname + "</p>" + answer; // doesn't work
//"<p><img src=\\" + "\"" + path + "\"" +"></p>"; // this doesn't work either
document.body.appendChild(oPara);
}
What am I missing here?

Is this example helps?
<!DOCTYPE html>
<html lang="en">
<head>
<title> Bla! </title>
<script type='text/javascript'>
function AddStudent() {
var studentData = { "name":"John Dou" }; // for the exmaple.
var paragraph = document.createElement('p');
// set any style
paragraph.innerHTML = "The student " + studentData.name + " added to the family";
document.body.appendChild(paragraph);
}
</script>
</head>
<body>
<button onclick='AddStudent()'> Add Student </button>
</body>
</html>

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

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>

Displaying my JSON in HTML

These are my Json arrays:
{"0":"1","id":"1","1":"2015-01-11 12:30:45","DateTimeCreated":"2015-01-11 12:30:45","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"benjiwjh","username":"benjiwjh"}
{"0":"4","id":"4","1":"2015-02-11 09:09:09","DateTimeCreated":"2015-02-11 09:09:09","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"LSH","username":"LSH"}
{"0":"7","id":"7","1":"2015-12-03 18:30:00","DateTimeCreated":"2015-12-03 18:30:00","2":"Unresolved","status_desc":"Unresolved","3":"SWJH","username":"SWJH"}
{"0":"12","id":"12","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"benjiwjh","username":"benjiwjh"}
{"0":"14","id":"14","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"CYJM","username":"CYJM"}
How am I supposed to use these to display my code in an HTML file?
I have a function to show the data but it does not work:
function showData(response) {
var data = JSON.parse(response);
var id = data.id;
var DateTimeCreated = data.DateTimeCreated;
var status_desc = data.status_desc;
var username = data.username;
myText.textContent= id + DateTimeCreated + status_desc + username;
}
I think you should have a div tag in your html template.
For example, in your HTML template, there should be a scope of codes:
<div id="sometext">
</div>
And in your JS script,
var textContent = id + DateTimeCreated + status_desc + username
sometext = document.getElementById("sometext");
sometext.innerHTML(textContent);
For more info, please visit http://www.w3schools.com/js/js_output.asp
Hope it would be helpful
Based on the question, I'm not entirely sure when you are using the showData function. However, here's a jsfiddle that shows that it works: https://jsfiddle.net/qyy2nvtz/1/
<p id='hello'></p>
var myText = document.getElementById('hello');
You need to get an element before you can display something in it. So, I've initialized 'myText' with a paragraph element with id 'hello'.
Additionally, make sure that the response that is being passed in to showData is a string before you parse it. If it's already an object, then it won't be parsed.
Here you have an example, you need a div element to refer like "js":
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="js">
</div>
</body>
<script type="text/javascript">
var myText= document.getElementById("js");
var data = JSON.parse(response);
var id = data.id;
var DateTimeCreated = data.DateTimeCreated;
var status_desc = data.status_desc;
var username = data.username;
myText.textContent = id + DateTimeCreated + status_desc +username;
</script>
</html>
Further reading: http://www.w3schools.com/dom/prop_element_textcontent.asp

How to show a string on a page

This is a really stupid question.
I have a javascript string variable for a name, and i want to display it where it says user like this:
"Hello, user!" --> "Hello, Chris!
Surely you could have found this answer out easily yourself :p
Put the name in a span and give it an ID
Hello <span id="name"></span>
Then set the text using getElementByID
var name = "Chris";
document.getElementById('name').innerHTML = name;
var user_name = 'Chris';
document.writeln("Hello, " + user_name);
I think document.write plus some string concatenation are what you're looking for:
var user = "Chris";
document.write("Hello, " + user + "!");
Something like this will do the trick.
var user = 'Steve';
document.write('hello ' + user);
If you need to target an element, you can use the usual methods, such as:
var user = 'Steve';
var thisOne = document.getElementById('thisOne');
thisOne.innerHTML = ('hello ' + user);
May as well throw in a jsfiddle so you can play around an experiment.
This is example of dislay string into span tag.
'+' operator uses for string concatenation.
<html>
<head>
<script>
var name = 'Chris';
var field = document.getElementById('show_string');
field.innerHTML( '"Hello, '+ name + '!"' );
</script>
</head>
<body>
<span id='show_string'></span>
</body>
</html>
You can concatenate the user's name with the rest of the string you want to display like so:
<p id="hello"></p>
<script type='text/javascript'>
var user_name = "Chris";
var hello_string = "Hello, " + user_name;
document.getElementById("hello").innerHTML = hello_string;
</script>

unable to display the last visited date

Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script.
window.onload = init;
function init() {
var now = new Date();
var last = new Date();
document.cookie = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toGMTString() + ";lastVisit=" + last.toDateString();
var lastVisit = document.cookie.split("=");
document.getElementById("lastVisitedOn").value = lastVisit[6];
}
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="lastVisitTester.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
Why is the time/date not getting set for the h tag ? What is wrong with the script ?
window.onload = function () {
var now = new Date(),
expires = now,
lastVisit = document.cookie.match(/lastVisit=([^;]+)/),
userName = 'somebody';
// 1. You should set month in standalone way
expires.setMonth(now.getMonth() + 2);
// 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd
document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString();
document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString();
// 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match)
// 4. You should test if it's not null also
if (null != lastVisit) {
// 5. You should use innerHTML property for set content
document.getElementById("lastVisitedOn").innerHTML = lastVisit[1];
}
// 6. But in general you should RTFM more :)
// 7. ps: And also use some standard frameworks for this -- not manual raw JS
}
Well there are some problems in your code.
As others has mentioned before:
The function "toGMTString()" is deprecated.
Use "toLocaleString()" or "toUTCString()" instead of "toGMTString()" (see also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString)
You should use innerHTML and you had your index wrong.
You cannot use document.cookie that way. Not sure way.
Example:
var now = new Date();
var last = new Date();
var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString();
document.cookie = cookieText;
var lastVisit = cookieText .split("=");
document.getElementById("lastVisitedOn").innerHTML = lastVisit[4];

Categories