Why won't JavaScript run? - javascript

I was making an HTML code editor, I tested all of the HTML tags I know and they all work, except for script tags.
When I type <script>something</script> into the text area and click a button, the script doesn't execute.
Please help! Here is the code:
<span id="finishedProduct">
<p>When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!</p>
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea></br>
<button type="button">Run Code!</button>
</form>
<script>
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>

Here is the working code:
<span id="finishedProduct">When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea>
<br/>
<button type="button" onClick="makeCode()">Run Code!</button>
</form>
<script type="text/javascript">
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here's a link to the JSFiddle: http://jsfiddle.net/Q2qLF/. I've removed some broken HTML, such as; a button shouldn't be contained in a anchor tag, I've added a 'onclick' in your button that will call the 'makeCode()' function and I've added the 'type="text/javascript"' into your script tag as this maximises compatibility.
Please let me know if you need any more help
I've updated my JSFiddle http://jsfiddle.net/Xanco/Q2qLF/1/
Now there are 2 textareas, one for the HTML and one for the Javascript. i've also created a new function called 'makejs', this takes the value of the Javascript textarea and runs it through a 'eval' - this executes the Javascript passed to it.

I've put the answer in a Fiddle here: http://jsfiddle.net/joshnicholson/P8eh9/
I'm not sure why you're wrapping the button element inside an anchor, but I would do it a slightly different way.
Here is the revised javascript:
var myButton = document.getElementById("btnRunCode");
myButton.addEventListener("click", makeCode);
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
I added an id of "btnRunCode" to your button element, just to make things easier for me. See the Fiddle.

Related

Not working handler on "onchange" event

I'm trying to make some changes in DOM after an image is selected with an "input file" HTML5 element. So, I added a handler to the "onchange" event, but it is not working!
<span class="btn-file" >
Load and show alert
<input type="file" onchange="performSomeActions()"/>
</span>
And supose this is the function:
function performSomeActions(){
alert("lalala");
}
The error I get when I execute the code and after choosing a file is:
Uncaught ReferenceError: performSomeActions is not defined
I thought maybe I was wrong with the event name, but if you replace the input definition with the following line, it is working!
<input type="file" onchange="alert('alo');"/>
THE FIDDLE: http://jsfiddle.net/pvhaggrv/5/
Thanks in advance!
JSFiddle doesn't like calls to javascript embedded in your html. In the interest of keeping your code clean event handlers are assigned via javascript instead.
Change your html to:
<input type="file" id='fileInput'/>
and then in your JS
document.getElementById('fileInput').onchange = function() {
performSomeActions();
}
working fiddle: http://jsfiddle.net/bmartinelle/rhbphvhu/
just put javascript function in body tag just before ending of body tag like this
<span class="btn-file" >
Load and show alert
<input type="file" id="file" onchange="performSomeActions();"/>
</span>
<br/>
<img id="img"> </img>
<script>
var performSomeActions=function(){
alert("yyy");
}
</script>
see fiddle
Your fiddle doesn't work because fiddle executes all your javascript in the a anonymous function:
//<![CDATA[
window.onload=function(){
function performSomeActions(){
alert("yyy");
}
}//]]>
So your function isn't in the global scope and your HTML can't see it.
To your code works you need to include your function directly at the HEAD, you can do this in fiddle changing the checkbox at the left side: http://jsfiddle.net/pvhaggrv/12/
HOWEVER, you should not add event listeners this way, you should use addEventListener like kougiland said in his answer.
DEMO
HTML:
<span class="btn-file" >
Load and show alert
<input type="file" id="input">
</span>
<br/>
<img id="img"> </img>
SCRIPT:
function handleFiles() {
alert("lol");
var fileList = this.files; /* now you can work with the file list */
}
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
SOURCE:
Dynamically adding a change listener

Escape HTML tag in <textarea>

I have one <textarea> tag in my website where the user can put there HTML code and see its preview. My problem is when the user enter code below mention in my <textarea> my preview functionality getting fail :
<html>
<textarea>Some code to show</textarea>
</html>
So question is how can I escape this html code in my <textarea> tag as I know the problem is coming because </textarea> tag.
Any solution on this please.
Edit
Question is about using </textarea> within a textarea.
Problem visible here: http://jsfiddle.net/hrP6F/
EDIT: for your purpose this would do:
<textarea>
Outside Textarea
<textarea>Inside Textarea</textarea>
</textarea>
source: How can I embed a textarea inside of another textarea in HTML?
Or use contenteditable like someone already mentioned -> click
FIRST ANSWER: Im not sure I understand perfectly but still. You want to display the code inside text area somewhere else for instance?
You could do that on click like this (I reckon you are not statically putting nested text areas in html?):
HTML:
<textarea id="textarea" >Something code to show</textarea>
<button onclick="show()">show</button>
<div id="showArea"></div>
JS:
function show(){
var t = document.getElementById('textarea').value;
document.getElementById('showArea').innerHTML = t;
}
This is of course if what you want is to display html that is inside textarea. you could also put another textarea inside first one and it will work.
If you want the results to display dynamically you could use
<textarea id="textarea" onkeyup="show()">Something code to show</textarea>
This works even if you put your code (html and text area) inside text area - it displays it, I tested it
You can add a output div for preview purpose. Below is the jQuery script
HTML
<textarea placeholder="Enter your html"><b>test</b></textarea>
Run
<div class="op"></div>
JS
$('.run').click(function(){
$('.op').html($('textarea').val());
return false;
});
DEMO

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Can't change onclick dynamically through javascript: bookmarklet

I've tried to change the onclick function through a bookmarklet in the url using this code:
javascript: document.getElementById('Button1').onclick = function(){alert('foo')};void(0);
I can change the value of the button but just not the onclick function. Is it even possible?
Thanks ^^
Some notes: I've also tried putting the code in a .js file and creating an external .js file using createElementId but it still does not seem to work :/
You were missing the trailing semi-colon to terminate the alert call. It's easier to spot once you indent it:
document.getElementById('Button1').onclick = function() {
alert('foo');
};
This code works. So the only option is that Button1 is not an ID of an element on that page.
For example:
<div id="Button1">Button</div>
If an element on the page looks like that, you will get your alert ('foo');
Your code seems to work...
Try to insert this code into the w3schools jseditor http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
<html>
<body>
<button type="button" id="Button1" onclick="alert('Some action');">Action!!</button>
<button type="button" id="Button2" onclick="document.getElementById('Button1').onclick = function(){alert('another action')};">Change onclick</button>
</body>
</html>

Javascript text field live view

I am trying to make a similar bit of code like at the bottom of this page to leave a comment. I have the basic code but the output does not register new lines (or HTML, but that isn't important). I have the function below called on key-up on the text field. Any help would be greatly appreciated. Thanks
Here is the whole page (Now working)
<html>
<body>
<form>
<textarea id="text" onkeyup="outputText()"></textarea>
</form>
<div id="outputtext" style="width:500px;">
</div>
</body>
<script type="text/javascript">
function outputText()
{
var text = document.getElementById('text').innerHTML;
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
}
</script>
</html>
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
Have you tried getting the textarea contents as
var text = document.getElementById('text').value; instead?
I think it's good for you to take a look at how tools like jQuery can make your live easier in this kind of cases. Your particular question is a bit unclear however...can you give us more details?
You can use the <pre> (preformatted) tag so that html and carriage returns are represented without doctoring the field input
html:
<input id="text" type="text" />
<pre id="outputtext"></pre>
jQuery:
$(document).ready(function () {
$('#text').keyup(function () {
$('#outputtext').html($(this).val());
});
});

Categories