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.
Related
I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});
I feel a bit silly asking this question, since most of the questions people ask on here are way beyond my level as a programmer, but at least I know I'm in good hands as far as asking goes. I used to know how to make simple vbscript and javascript programs, but I'm a bit rusty. I'm trying to refresh myself, and despite repeated google/other searches, can't recall how to make it so that when a button is clicked, a msgbox appears. Also, I'd like to know how to modify the .value attribute of a textbox. I'm attempting this in vbscript for now, but I'll try javascript if anyone knows a way to do it in that instead. My ultimate goal is a text based type game where you can click buttons labeled, "north,south,west,east", and make it like an rpg. The textbox would display the current room description.
Here's the code I have so far, which isn't displaying the msgbox.
<html>
<title>Explor-o-Rama!</title>
<body>
<form name = frmMain>
<textarea name = "txtDisp" rows = "10" cols = "50"></textarea><br>
<input type = "button" name = cmdTest value = "test">
</form>
<script language = "vbscript">
sub cmdTest_OnClick
msgbox "test"
end sub
<script>
</body>
</html>
You have:
msgbox "test"
The correct command is:
MsgBox("test")
OR
X=MsgBox("test")
This SHOULD DO IT.
also, <html><body><script language=vbscript>msgbox "" </script></body></html> not works.
but this code works OK:
<html><body><script>alert('Test');</script></body></html>
<html>
<body>
<script>
function test()
{
alert('Test');
}
</script>
<input type = 'button'; onclick='test()'>
</body>
</html>
Probably, it's a IE internal bug.
I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.
Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.
I'm rolling my own version of prompt() for aesthetic purposes; it's come along quite nicely as far as visuals go, but I have run into a slight hitch: the native version of the function causes code execution to cease completely until the prompt has been dealt with.
This is positively lovely and it's why the below works the way it does:
<script>
var c = prompt('Name?', '');
alert(c); // displays whatever the user entered
</script>
With my method, however, things do not go as smoothly. I am using a dialog, an input box, and an OK button to gather the data from the user; to my knowledge, data collection works perfectly; that is, I know for sure that after the user presses the OK button, I have access to the data they just put into the prompt.
I cannot, however, find a way to get my version to work as the native one does. My question, then, is this: is it at all possible to tell JavaScript to halt executing until you've told it to resume?
Thanks in advance for any and all assistance.
No, it is not possible to duplicate this behavior. The way to achieve the same effect is to use a callback in your code, so you can do something like:
myPrompt('Hello, mate, whats yer name?', function(answer) {
alert(answer);
});
EDIT: Based on your code, why not do this?
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(prompt, callback) {
$('prompt').style.display = '';
$('q').value = '';
$('ok').onclick = function() {
callback($('q').value);
}
}
_prompt('Name?', function(answer) {
alert(answer);
});
</script>
</body>
If you change alert(answer); to say... gAnswer = answer; (notice no var declaration) you would be creating a global variable named gAnswer that you could access anywhere else in the javascript code, assuming the prompt was already answered. If you're concerned of global variables polluting your space you could wrap it all in a closure, but it should be fine otherwise.
#Paolo:
This is the code I am currently working with:
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(q, e)
{
$('prompt').style.display = '';
$('q').value = '';
$('ok').setAttribute('onclick', e + ' $("prompt").style.display = "none";');
}
var c; _prompt('Name?', 'c = $("q").value;');
alert(c);
</script>
</body>
Now, as would be expected, that alert() fires as soon as the page is loaded, which is most definitely not what I want; ideally, I'd like for the rest of the code to wait for the prompt to get handled, but I'm strongly doubting this is possible outside of the native implementation. Reckon I'll just have to settle for designing my algorithm so that the prompt gets used immediately?