Reputation: 174
I want to create a JavaScript Command Execution .. I mean, if I build up a page, with an input method, then, the value of that input method is executed in the JavaScript console, then, the result of that execution should be inserted in an HTML tag as: HTML:
<input id="commandInsertion"/>
<input type="Submit" onclick="doCommand()">
<p id="result"></p>
JavaScript:
var doCommand = function(x) {
// The command should be something like this
Execute(x); // Imaginary Function
document.getElementById('result').innerHTML = ResultOf(x);
// ResultOf() is also an imaginary function
};
doCommand
is a function that executes a command and then, prints it into the document
Upvotes: 0
Views: 366
Reputation: 530
What I got from your explaining that you need some thing such as the following:
function getInsertedValue() {
var txt = document.getElementById('commandInsertion').value;
updateElem(txt);
}
function updateElem(insertedTxt) {
document.getElementById("updatedTxt").innerHTML = eval(insertedTxt);
}
<div>
<input type="text" id="commandInsertion" />
<span id="updatedTxt"></span>
<input type="Submit" onclick="getInsertedValue()">
</div>
Upvotes: 1
Reputation:
Simple. Heard of eval
? It is a fun and dangerous function. It allows you to evaluate code during runtime. Here's an example:
$('#calc').on('input', function() {
try {
$('#out').val(eval($('#calc').val()));
} catch (e) {
$('#out').val('ERROR!')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Input:
<br>
<input id='calc'>
<br>Output:
<br>
<input id='out'>
It's simple, but eval can also be dangerous. It can allow attackers to do anything you can do. You might want to read up on this:
Restricting eval() to a narrow scope
So here's the code you want:
var doCommand = function() {
// The command should be something like this
document.getElementById('output').innerHTML = eval(document.getElementById('commandInsertion').value);
};
<input id="commandInsertion" />
<div id="output"></div>
<br>
<br>
<input type="Submit" onclick="doCommand()">
Upvotes: 3