Currently, you can use the user's final script. This script can modify some previously available variables.
I created a small example in pure javascript I would like to do the same in angular 2+ https://jsfiddle.net/hxs3d0hu/2/
Thank you in advance for your attention
HTML Code
<div class="container">
<form>
<div class="form-group">
<label for="descricao">Nome</label>
<input type="text" id="descricao" name="descricao" class="form-control" />
</div>
<div class="form-group">
<label for="valor">Valor</label>
<input type="text" id="valor" name="valor" value="10" class="form-control" />
</div>
<div class="form-group">
<label for="quantidade">Quantidade</label>
<input type="text" id="quantidade" name="quantidade" value="20" class="form-control" />
</div>
<div class="form-group">
<label for="total">Total</label>
<input type="text" id="total" name="total" class="form-control" />
</div>
<div class="form-group">
<label for="codex">Code</label>
<textarea id="codex" name="codex" rows="10" cols="100" class="form-control">
if (qtde < 15) {
vlr = 10;
}
else
{
vlr = 9;
}
tot = vlr * qtde;
</textarea>
</div>
<button type="button" id="calcular" name="calcular" onclick="calcularx();" class="btn btn-primary">Calcular</button>
</form>
</div>
JavaScript Code
var vlr = 0;
var qtde = 0;
var tot = 0;
function calcularx(){
var valor = document.getElementById("valor");
var quantidade = document.getElementById("quantidade");
var total = document.getElementById("total");
vlr = valor.value;
qtde = quantidade.value;
tot = 0;
tot = qtde * vlr;
total.value = tot;
var codex = document.getElementById("codex").value;
var cst = document.getElementById("customcodescript");
var corpo = "function custom(){ {0} }".replace("{0}", codex);
//cst.innerHTML = corpo;
load_js(cst, corpo);
custom();
valor.value = vlr;
quantidade.value = qtde;
total.value = tot;
console.log(tot);
}
function load_js(cst, corpo)
{
if(cst != null){
cst.remove();
}
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.id = "customcodescript";
script.type= 'text/javascript';
script.innerHTML = corpo;
//script.src= 'source_file.js';
head.appendChild(script);
}
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
Here's a plnkr that would achieve what you're looking for.
http://embed.plnkr.co/w2FVfKlWP72pzXIsfsCU/
You create a function with eval, then call it using the component context. All the function and variable in your component will be available to your textbox code :
The template
Value:
<label>Code:</label>
<textarea [(ngModel)]="code"></textarea> <br>
<button (click)="executeCode(code)">Do it.</button>
The component :
export class HelloWorld {
value = 100;
code = 'this.value = this.value * 100';
executeCode(code){
let fn = eval("(function(){ {0} })".replace("{0}", code));
fn.call(this);
}
}
However, keep in mind that eval is usually evil and that this use case is quite weird. I'm not sure if your user should control the code. Anyhow, that's up to you.
Also, if you want to avoid the "this." in the code text box, you can always use replace on your variable name to add it behind the scene.
Related
I have been trying to get the values from the textView box but it's not displaying in the p field at all, and also I am trying to add the 2 values together into one value and display it.
function() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + x.elements[i].value;
}
document.getElementById("demo").innerHTML = text;
}
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="123"><br>
Last name: <input type="text" name="lname" value="123"><br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
You need to call the function on the document load. And make these changes inside the function
var myValue = 0;
for (i = 0; i < x.length; i++) {
if (x.elements[i].type === "text")
myValue += Number(x.elements[i].value);
}
document.getElementById("demo").innerHTML = myValue;
Try this. In your code.
document.getElementById("demo").innerHTML =
myfunction(document.forms["frm1"]);
should be called outside the function. Also, you should include a name for the function you've created.
function myfunction(input) {
var text = "";
for (var i = 0; i < input.length; i++) {
text += input[i].value;
}
return text;
}
document.getElementById("demo").innerHTML = myfunction(document.forms["frm1"]);
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
<label>First name:</label> <input type="text" name="fname" value="123" /><br>
<label>Last name:</label> <input type="text" name="lname" value="123" /><br><br>
<input type="submit"/>
</form>
<p id="demo"></p>
I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}
I want to improve my Password Generator. I want that the user can choose what the password should include. For example you can choose that the password has letters but no numbers and characters. Can someone say me what i have to do?
here is my javascript and html:-
function randomPassword(length) {
var chars = "abcdefghijklmnopqrstuvwxyz!##$%^&*()-+<>ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var pass = " ";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
<form name="myform" method="post" class="form-horizontal">
<div class="form-group " >
<div class="col-sm-10">
<br>
<input class="rowpassword" type="text" name="row_password" size="45s">
<br>
<input class="form-control passwordlength" type="text" name="length" value="8" > password length
<br>
<br>
<input type="checkbox"> Groß - und Kleinbuchstaben
<br>
<input type="checkbox"> numbers
<br>
<input type="checkbox"> specialcharacters
<br>
<br>
<input type="button" class="form-control button" value="Passwort generieren" onClick="generate();" tabindex="2">
</div>
</div>
</form>
Firstly, check for the checked property for the checkboxs.
Then you can decide whether to have more than one pool of characters, or to apply filters which depend on what is checked.
For the former, you can add the appropriate pools together, so something along the lines of
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>"
var numberPool="1234567890"
if(characterType.checked)
{
chars+=characterTypePool;
}
etc.
If you do this, don't forget to have error handling for when none are selected.
UPDATE:
I've added a snippet (minus error handling) to demonstrate (don't forget to check the boxes!)
function randomPassword(length) {
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>";
var numberPool="1234567890";
if(document.getElementById('letters').checked)
{
chars+=letterPool;
}
if(document.getElementById('numbers').checked)
{
chars+=numberPool;
}
if(document.getElementById('speChars').checked)
{
chars+=specialPool;
}
var pass = " ";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
<form name="myform" method="post" class="form-horizontal">
<div class="form-group " >
<div class="col-sm-10">
<br>
<input class="rowpassword" type="text" name="row_password" size="45s">
<br>
<input class="form-control passwordlength" type="text" name="length" value="8" > password length
<br>
<br>
<input type="checkbox" id='letters'> Groß - und Kleinbuchstaben
<br>
<input type="checkbox" id='numbers'> numbers
<br>
<input type="checkbox" id='speChars'> specialcharacters
<br>
<br>
<input type="button" class="form-control button" value="Passwort generieren" onClick="generate();" tabindex="2">
</div>
</div>
</form>
UPDATE TWO:
To guarantee that there will be at least one of each selected character type, you would need to add code. one way is to choose one at the start, and to add it to a random position in the final password. The following adaptation of the code does so by using an array and splice:
function randomPassword(length) {
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>";
var numberPool="1234567890";
var guaranteed="";
if(document.getElementById('letters').checked)
{
chars+=letterPool;
guaranteed+=letterPool.charAt(Math.floor(Math.random() * letterPool.length));
}
if(document.getElementById('numbers').checked)
{
chars+=numberPool;
guaranteed+=numberPool.charAt(Math.floor(Math.random() * numberPool.length));
}
if(document.getElementById('speChars').checked)
{
chars+=specialPool;
guaranteed+=specialPool.charAt(Math.floor(Math.random() * specialPool.length));
}
var pass =[];
for (var x = 0,len=length-guaranteed.length; x < len; x++) {
var i = Math.floor(Math.random() * chars.length);
pass.push(chars.charAt(i));
}
for(var x = 0,len=guaranteed.length; x < len; x++)
pass.splice(Math.floor(Math.random() * pass.length),0,guaranteed.charAt(x));
pass=pass.join('');
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
I am trying to get the value of an input and display it in a div under it, while the user is typing. and i want to do it with vanilla js. no j query.
MY HTML:
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>
MY JS:
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementsByClassName('displayQuestion');
function myDisplay(e){
showQuestion.innerHTML = input;
}
Try this:
function myDisplay(e) {
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementById('displayQuestion');
showQuestion.innerHTML = input;
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay(this.value)"/>
</div>
<div id="displayQuestion"></div>
Here you go with VannilaJS way,
Recommendation: Change the name of the function myDisplay() to something meaningful like displayQuestion()
var targetElm = document.getElementsByClassName('displayQuestion');
var inputElm = document.getElementById('inputText');
function myDisplay() {
if(targetElm && targetElm.length > 0){
targetElm[0].innerHTML = inputElm.value;
}
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size ="50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>
Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/