I'm completely new to Javascript and trying to learn some basics
I'm making a webpage that add's up totals etc and right from the start i'm having a problem.
I'm looking at videos on lynda.com and i've also searched the net.
it's something very simple i'm trying to do.
I have a variable set to 30 and I want to display that on my page.
var points = 30;
document.write(points);
I also had 30 in double and single quotes which didn't work.
My HTML is
<p id="points"></p>
What I want to happen is I want the variable to display on site. So in this case I want 30 to display on site.
it's not at the moment.
Any help would be great.
thanks.
The correct code is:
var points = 30;
document.getElementById('points').innerHTML = points;
Use innerHTML for change the HTML code and use innerText to change only the text.
Maybe you forgot to implement the script:
<script src="path/and/yourscriptname.js"></script>
<p id="points"></p>
An easier method to peek into variables at certain points is to use console.log().
For example, console.log(points); will output 30 so your browser console.
To view the browser console, Google how to view the console for the specific browser you're using. Here's how to view it on Chrome.
Related
I have a simple search engine on one of our older websites. This site is running IIS 6.0 on Windows Server 2003. The search functionality is provided by Microsoft Indexing Service.
You can see the search functionality on our website. (Just type in "speakers" and you will see some hits.
I would like to use the "FullHit" feature offered by the indexing service. When using this feature the Indexing service inserts the full hit results in between "begindetail" and "enddetail" on a target web page.
The problem that I have is that the documents that are being returned have HTML. This looks messy. (Just click on "Hit Locator Tool" in the search results above to see what I mean.)
I would like to create a DIV section such as ...
<DIV name="target">
begindetail
enddetail
</DIV>
Then, after the page is populated I would like to use javascript to strip out all of the HTML elements (but not the data) between the opening and closing DIV.
For example, <FONT color="magenta">Good Data</FONT> would be modified to only show Good Data.
I can also use Classic ASP if necessary.
Please let me know if you have any suggestions or know of any functions that I can add to the target page to accomplish this task.
Thanks in advance.
I inspected your webpage, and there definitely must be some logic errors in your ASP code. (1) Instead of something like <div></div> being passed to the browser, it is HTML entities for special characters, so it is being passed like <DIV> </DIV>, which is very ugly and is why it is rendering as text instead of HTML code. In your ASP code, you must not be parsing the search result text before passing it to the browser. (2) All of this improperly-formatted code is inserted after the first closing html tag, and then there are closing body and html tags after the improperly-formatted code, so somewhere in your ASP code, you are telling it to append the code to the end of the document, rather than insert it inside the original <body></body>.
If you want to decode the mixture of HTML entities, <br> tags, and text into rendered HTML, this JavaScript may work:
window.onload = function() {
var text = decodeHTMLEntities(document.body.innerText);
document.write(text);
}
function decodeHTMLEntities(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
return text;
}
jsFiddle: https://jsfiddle.net/6ohc1tkr/
But first things first, you need to fix your ASP code, or whatever you use to parse and then display the search results. That's what is causing the improper formatting and display of the HTML. Show us your back-end code and then we can help you.
This is what I used to accomplish what you are trying to do.
string-strip-html
It worked pretty well for me.
I now have the search feature working as expected. I would like to thank everyone for their insightful comments. This feedback helped me identify and fix the problem.
OS: Windows Server 2003
IIS: 6.0
Microsoft Index Server
The hit locator tool will only work properly for HTML pages. If you use this tool with a simple TXT file then the results will not be displayed correctly.
I created a code through Codecademy. Whenever I wanted text to appear, I was told to use console.log However, when I actually run the code, using HTML (as a js file would not run), the text does not appear, as the console is not displayed.
The code was for one of those classic choose-your-adventure text-based games. After answering a prompt, text with the story line is supposed to appear as another prompt appears. The prompts run through, but the story line is not displayed. What could I change console.log to in order to make the text appear?
~EDIT~ Thank you, Vince.
I suppose some of you did not exactly understand what I was asking.
I shared my reason for my ignorance. I learned JavaScript through Codecademy. They did not teach you how to make text appear. All they said was you could use console.log to make text appear. It makes text appear in the console, but I wanted it to appear outside of the console.
I went back to my script and changed every console.log to document.writeln. My code now works.
And to whoever suggested that I would be afraid of JavaScript: I wrote a lengthy and complex code for a beginner. I did not post it on here as it is my intellectual property and I did not need to post it to ask my question. I had a misconception and I wanted to clear it up.
Though essentially considered bad practice, (but as a beginner you're more than welcome to use this) you can use document.writeln('Hello, World!'); to actually write text onto the page.
You can also, in your HTML, define a container with an id:
<div id="my-text-box">
</div>
and in your JavaScript,
window.onload = function(){
document.getElementById('my-text-box').innerHTML = "Hello, World!";
};
I'm not entirely sure what you want to achieve, but I guess you want to display text on your webpage. You can do this like this:
window.onload = function() {
var a = 'Text to be displayed'; //<<< The text you want to display
var b = document.createElement('div'); //<<< create a Element
b.innerHTML = a; // <<< append content to the element
document.getElementsByTagName('body')[0].appendChild(b); //<<< append the element to the pages body
}
I'm very new to javascript so please forgive me this if it's actually a crazy simple thing to do, but I've been googling and going through all my reference sites with no luck. What I'm trying to do is display a variable's value and change the value the variable either +1 or -1 when the user clicks the appropriate button - like this.
Can anyone help me? Thanks!
The following is an example you can work with. It's a full HTML page, which you can open in a web-browser to see in action. Copy and paste it into a text-file, which you save as example.html. Open it in notepad or something similar to edit it.
This is just one simple example - there are many ways to do stuff like this. Google around, see examples, and play around with them, and it will make sense, bit by bit.
Though it is old, and not always perfect, the examples at W3C may still be a good place to start if you want to know more.
<html>
<head>
<script type="text/javascript">
var currentValue = 0;
var add = function(valueToAdd){
alert("adding: " + valueToAdd);
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;
};
</script>
</head>
<body>
<div id="text">Number of eggs:<span id="number">0</span><div>
Plus 1
Minus 1
</body>
</html>
UPDATE: One little addition: If you want a fairly new and good book on Javascript, and want to learn it "correctly", then JavaScript: The Good Parts is probably the book you want. It is not a big book (just under 100 pages if I remember correctly), but gives a nice overview of the language.
can anyone explain what happens when you use javascript to insert a javascript based widget?
here's my js code:
var para = document.getElementsByTagName("p");
var cg = document.createElement("div");
cg.setAttribute("class", "twt");
cg.innerHTML='<a href="http://twitter.com/share" class="twitter-share-button"
data-count="vertical" data-via="xah_lee">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
document.body.insertBefore(cg, para[1]);
it inserts the twitter widget, before the first paragraph. As you can see above, the twitter widget calls for a javascript that shows how many time the page has been tweeted.
doesn't work in Firefox, Chrome, but semi-works in IE8. What should be the expected behavior when this happens? Does the newly inserted js code supposed to execute? If so, how's it differ from if the code is on the page itself?
In order to execute the JS code you insert into a DIV via innerHTML, you need to do something like the following (courtesy of Yuriy Fuksenko at http://www.coderanch.com/t/117983/HTML-JavaScript/Execute-JavaScript-function-present-HTML )
function setAndExecute(divId, innerHTML) {
var div = document.getElementById(divId);
div.innerHTML = innerHTML;
var x = div.getElementsByTagName("script");
for (var i=0;i<x.length;i++) {
eval(x[i].text);
}
}
A slightly more advanced approach is here: http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/ - look for <script> tags, take their conĀtent and create a new eleĀment into the <head>.
innerHTML does not work to insert script tags (because the linked script, in most browsers, will fail to execute). Really, you should insert the script tag once on the server side and insert only the link at the location of each post (that is, if you are adding this to a blog home page that shows multiple posts, each with their own URLs).
If, for some reason, you decide that you must use one snippet of JavaScript to do it all, at least import the tweet button script in a way that will work, for example, the Google Analytics way or the MediaWiki way (look for the importScriptURI function). (Note that I do not know the specifics of the tweet button, so it might not even work.)
I'm trying to dynamically add some textboxes (input type=text) to a page in javascript and prefill them. The textboxes are coming up, but they are coming up empty. What is the proper way to pre-fill a textbox. Ideally I'd love to use the trick of creating a child div, setting the innerhtml property, and then adding that div to the parent main div but that didn't work. Then I thought I'd use the dom but setting textboxname.value before or after insertion won't work and doing txttextbox.setattribute('value','somevalue') won't work either. Works fine in firefox. What gives? This has to be possible? Here is my code. I know I'm only using string literals, but these will be replaced with the results of a web service call eventually. Below is some code. Oh and how do you format code to show up as you type it? I thought it said to indent four spaces, and I did that but the code is still on one line. Sorry about that.
var table=document.createElement('table');
var tbody=document.createElement('tbody');
var row=document.createElement('tr');
row.appendChild(document.createElement('td').appendChild(document.createTextNode('E-mail')));
var txtEmail=document.createElement('input');
row.appendChild(document.createElement('td').appendChild(txtEmail));
tbody.appendChild(row);
table.appendChild(tbody);
//document.getElementById('additionalEmails').innerHTML="";
document.getElementById('additionalEmails').appendChild(table);
txtEmail.value = 'my text'
Does not work?
You can also use Prototype to do this easily:
document.body.insert(new Element("input", { type: "text", size:20, value:'hello world' }))
I've encountered problems similar to this in the past, and while my memory is a bit fuzzy on why it was happening exactly, I think you may need to make sure the element is actually added to the DOM before modifying its value. e.g:
var txtEmail=document.createElement('input');
document.getElementById('someElementThatAlreadyExists').appendChild(txtEmail);
txtEmail.value = 'sample text';
I ended up solving this problem by injecting the html directly into a page via a child div. That did work, it's just that I am blind and the software I use to read the screen for some stupid reason failed to see the text in the textbox. Go figure. Thanks for the tip on prototype though, if I ever decide not to cheat and add the eleements to the dom directly, I'll do it that way.