Ziad Amerr
Ziad Amerr

Reputation: 174

Javascript command insertion HTML

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

Answers (3)

mustafa-elhelbawy
mustafa-elhelbawy

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

user5330911
user5330911

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

Igal S.
Igal S.

Reputation: 14543

Don't you just mean eval function?

The eval() function evaluates or executes an argument.

Use it very carefully - at it allows the user to run any javascript command and that is a big security risk.

Upvotes: -1

Related Questions