I have a page that accepts Javascript code in a text area. I would like to run that code when the user presses the run button.
Is the following possible:
var programFunction = new Function(document.getElementById('program').value);
<button type="button" onclick="programFunction">run</button>
Let's say the textarea program has the following in it:
document.getElementById('program').value = 'Tested';
When I try to test this myself, I don't get any errors but I also don't get any output.
You need your "run" button to process and run the code.
At its simplest, it's just:
onclick="eval(document.getElementById('program').value);"
Note that in this case, eval is perfectly okay provided that the value of the program field can only come from the user's own input, and not anyone else's.
There are a couple of things wrong in your code:
It seems like you try to access the content of the textarea before it got a value.
You don't run the function you created.
You have to retrieve the value of the texarea when the button is pressed, not before. Still using Function, it would look like:
<script>
function runCode() {
var source = document.getElementById('program').value;
var func = new Function(source);
func();
}
</script>
<button type="button" onclick="runCode()">run</button>
Related
So, I have the following code, and it's not working, and I'm not sure why. Any suggestions?
HTML:
<input type="number" placeholder="#" id="lineSpace"/>
<br/><br/><button id="go">update text!</button>
JavaScript (jQuery)
$(document).ready(function() {
var lineSpace = $("#lineSpace").val();
$("#go").click(function(){
alert("LINE SPACE: "+lineSpace+"");
});
This was a test to see if my variable was being gathered, but it seems not. The alert appears but simply says "LINE SPACE: ", without placing the variable after it. When I define the like this var lineSpace = "random number";(which is no use to me, as I need a value that is entered from the user-side), however, it works fine.
Because you are assigning lineSpace when the page loads, and it's obviously blank then.
Move var lineSpace = $("#lineSpace").val(); into your click handler (above the alert() function call).
I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
The button is not finding the update() method. You need that function to be globally available:
http://jsfiddle.net/t5swb7w9/1/
UPDATE: I understand now. Internally jQuery basically evals script tags. There's too much going on to be worth replicating yourself... either use a library to append, or eval the code yourself. Just a warning that eval'ing user input is rarely a good thing and is usually a welcome mat for hackers.
window.myScope = {
update: function() {
var div = document.createElement('div'),
codeinput = document.getElementById('codebox').value,
scriptcode = "";
div.innerHTML = codeinput;
Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
scriptcode += ";" + script.innerHTML;
div.removeChild(script);
});
window.frames[0].document.body.appendChild(div);
// hackers love to see user input eval'd like this...
eval(scriptcode);
}
};
And then you would update your button like so:
<input id="button" onclick="myScope.update();" type="button" value="Update page">
Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)
JavaScript inserted via innerHTML will not be executed due to security reasons:
HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try it here
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.
I see that when I try to read the value from a textarea field when its onpaste function is called, I get the old value of the field (the one before the paste operation), not the new value (the one after the paste operation).
Here is a demonstration of this behaviour: http://jsfiddle.net/qsDnr/
A copy of the code follows:
<!DOCTYPE html>
<html>
<head>
<title>On Paste</title>
<script type="text/javascript">
var textareaElement;
var previewElement;
function update()
{
previewElement.innerHTML = textareaElement.value;
}
window.onload = function() {
textareaElement = document.getElementById('textarea');
previewElement = document.getElementById('preview');
textareaElement.onpaste = update
}
</script>
</head>
<body>
<textarea id="textarea">
</textarea>
<div id="preview">
</div>
</body>
</html>
You can confirm the behaviour with the following steps.
Copy the string foo to your clipboard.
Right-click on the textarea field and select 'Paste'. Nothing appears in the div element.
Right-click on the textarea field and select 'Paste' again. foo appears in the div element.
Since I want the div element to always show what was updated in the textarea element with the paste operation, the desired output is foo and foo foo in step 2 and step 3 respectively.
One way I have managed to get the desired output is by delaying the update() function call with window.setTimeout(), so instead of
textareaElement.onpaste = update
I have got
textareaElement.onpaste = function() {
window.setTimeout(update, 100);
};
this time (demo: http://jsfiddle.net/cwpLS/). This does what I want. However, this feels more like a workaround rather than a straightforward way of doing what I want. I would like to know if there is any alternate or better way to do this.
I'm pretty sure that you setTimeout solution is the only way to achieve the desired effect, or try to access the clipboard object - which can get messy if you're going for cross-browser & old browser support.
There is no direct way to do it in cross browser. See the link below about the behaviour in firefox.
Mozilla
There is currently no DOM-only way to obtain the text being pasted; you'll have to use an nsIClipboard to get that information.
Also please have a look at the stackoverflow link which discuss about other possibilities.
I've been looking at this code:
http://www.jquery4u.com/jquery-date-and-time-2/online-jquery-stopwatch/
I'm trying to understand exactly how it is working because I'd like a timer on a page I'm working on.
I can't for the life of me work out where the value of the timer is added to the input "disp" and how I could put this into a regular text, not a form input.
The only thing I can see that refers to it is:
t[6]=document.getElementById('disp');
Can anyone help me understand this please,
Thanks
You've correctly identified that they use t[6] to refer to the HTML element. But to set it, earlier on there is:
function disp() {
if (t[2]) t[1]=(new Date()).valueOf();
t[6].value=format(t[3]+t[1]-t[0]);
}
Since t[6] is the form input, they set the value of the form input to the formatted time. If you wanted to use some other element, e.g. <div id="myTime"></div>, you could say instead:
function disp() {
if (t[2]) t[1]=(new Date()).valueOf();
document.getElementById("myTime").innerText = format(t[3]+t[1]-t[0]);
}
Which changes only the last line, so that you may set the text of your div.
I have an <input> in my document. There I want the user to do some input.
var myVar = document.getElementById('userInput').value;
Then I want this value to be shown in another <input>.
document.getElementById('Preview').value = myVar;
This code somehow doesn't work.
Can anybody help?
Thanks in advance!
Update based on further information in comments before:
<button onClick="calculateThatObscenityDeleted()">"Save"</button >
Submit buttons will submit forms, thus running the JS but immediately blanking the form.
(That might still not be the actual issue, the question is still missing most of the code)
Original answer before it was revealed that the question didn't reflect the problem:
var myVar=document.getElementById('userInput').value;
Don't forget the =.
(And, obviously, you need to use that code in an event handler so it isn't executed only when the document loads and before the user has typed anything.)
Is it form?
Try something like this:
oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = 'Some Value';
Besides the typo, you have to bind an event handler to the first <input>:
var input_a = document.getElementById('userInput');
var input_b = document.getElementById('Preview');
input_a.onkeyup = function(){
input_b.value = input_a.value;
}