HTML Input Form to a Javascript Variable - javascript

I'm trying to implement an HTML form input, of which will take the numerical value and convert it into a variable in Javascript. This will then be used with chartjs to plot an graph.
I have the graph fully functioning if I input the variable separately, as used in the code below. I have been trying to use a function to take the value from the HTML form.
var force = 10
var numberOfPointLoads = 1
var pointLoadLocation = 5
var beamLength = 10
var supportCondition = "simplySupported"
var split = beamLength //No. of Finite Elements
var splitArrayYAxis = Array.from({
length: (split + 1)
}, (x, i) => i);
var yAxis = splitArrayYAxis.map(x => (x * (beamLength / split)));
yAxis.push(pointLoadLocation)
yAxis.push(pointLoadLocation)
yAxis.sort(function(a, b) {
return a - b
});
var splitArrayXAxis = Array.from({
length: (split + 1)
}, (x, i) => i);
var xAxisEnd = splitArrayYAxis.map(x => (x * (beamLength / split)));
xAxisEnd.push(pointLoadLocation)
xAxisEnd.sort(function(a, b) {
return a - b
});
var xAxisStart = xAxisEnd.splice(0, (xAxisEnd.indexOf(pointLoadLocation) + 1));
xAxisEnd.unshift(pointLoadLocation);
var shearForce = force / 2
var xAxisStart = xAxisStart.map(x => (shearForce))
var xAxisEnd = xAxisEnd.map(x => (-shearForce))
var xAxis = xAxisStart.concat(xAxisEnd)
var data = yAxis.map((v, i) => ({
x: v,
y: xAxis[i]
}));
//chart is below this
new Chart(document.getElementById("shearPointLoad"), {
type: "scatter",
data: {
datasets: [{
label: "MyScatter",
lineTension: 0,
data: data
}]
},
options: {
stacked: false,
bezierCurve: false,
title: {
display: true,
text: 'Plot of the Scatter'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="shearPointLoad" width="400" height="250"></canvas> Force Input <input type="text" id="userInput"></input>
<button id="submitter">Submit</button>
<div id="output"></div>
The variable will be equal to the value of the HTML and will be reassigned when updated.
Thanks for any help.
EDIT
let someInput = document.getElementById('someInput')
function onButtonClick() {
let someVariable = parseFloat(someInput.value);
console.info(someVariable);
}
var force = "someVariable"
var numberOfPointLoads = 1
var pointLoadLocation = 5
var beamLength = 10
var supportCondition = "simplySupported"
var split = beamLength //No. of Finite Elements
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="shearPointLoad" width="400" height="250"></canvas>
<input id="someInput" type="number" <input/>
<button onclick="onButtonClick()">Click me</button>

Add onclick event to the button and define a function plotchart():
<button id="submitter" onclick="plotchart()">Submit</button>
Now, to read the input value in the function:
var data = document.getElementById("userInput").value;
Now, wrap all you chart plotting code inside plotchart() function.

You need to use the button event onclick, so every time you click it, you can then grab the input's value using a reference to the element. Like the following snippet:
let someInput = document.getElementById('someInput')
function onButtonClick() {
let someVariable = parseFloat(someInput.value);
console.info(someVariable);
}
<input id="someInput" type="number" />
<button onclick="onButtonClick()">Click me</button>
After this, you may use someVariable for anything you need.
Notes:
Use a type="number" input for better UX (so users can't input text or some other characters)
Consider resetting the input value after clicking the button.

Related

Convert CreateElement to backtick not work

I am working on "createElement" with "backtick". Because it works faster. I will add 4-5 elements. So I want to use "backTick".
I tried to convert the "createElement" clause to "Backthick". But I get the error message "ReferenceError: Grid not defined".
I'm could not define the variable ri into "backtick".
var test = function (ui) {
let ri=ui.rowIndx;
var renkEkle = document.createElement('input');
renkEkle.type = "button"
renkEkle.value = "Mavi"
renkEkle.addEventListener('click', function(){
console.log('createElement',this);
grid.addClass({rowIndx: ri, dataIndx: 'ADATE', cls: 'mv'});
SatirDegistir(ri,['ADATE','OD_R1'],['2020-06-01','td']);
});
}
var test = function (ui) {
let ri=ui.rowIndx;
var renkEkle = `<input type="button" onclick="console.log('BackThicks',this);grid.addClass({rowIndx: 1, dataIndx: 'ADATE', cls: 'mv'});SatirDegistir(1,['ADATE','OD_R1'],['2020-06-01','td']);" value="Mavi">`;
}
Line 149-161
Line 149-161 Picture:
Line 149-161 Code:
var $inp = ui.$cell.find("input"),
grid = this,
validate = function (that) {
var valid = grid.isValid({
dataIndx: ui.dataIndx,
value: $inp.val(),
rowIndx: ui.rowIndx
}).valid;
if (!valid) {
that.firstOpen = false;
}
};
console.log('grid=',grid);
var renkEkle = `<input type="button" onclick="console.log('BackThicks',this);grid.addClass({rowIndx: 1, dataIndx: 'ADATE', cls: 'mv'});SatirDegistir(1,['ADATE','OD_R1'],['2020-06-01','td']);" value="Mavi">`;

If the input I put blank, then it will count 0

I am trying to put some amount, then it will show the calculation if all input will given any number, but I want, when I do not put anything in any one of that input, then the input will count "0" automatically..
<body>
<input type='text' id='aaa'/>
<input type='text' id='bbb'/>
<input type='text' id='ccc'/>
<input type='text' id='answer' name='ans' />
<form name ="testarea" Method="GET" Action="" id='form1'>
<input type="button" onClick="Calculate();" value="calculate"/>
</form>
</body>
<script>
function Calculate()
{
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = parseFloat(aaa) * 82;
var permin1 = parseFloat(bbb) * 40;
var permin2 = parseFloat(ccc) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
document.form1.submit();
}
</script>
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = (parseFloat(aaa)||0) * 82;
var permin1 = (parseFloat(bbb)||0) * 40;
var permin2 = (parseFloat(ccc)||0) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
You can use the OR operator to replace NaN with 0 if parseFloat returns NaN.
You could shorten the upper code to:
const ids = ["aaa","bbb","ccc"];
const factors = [82,40,10];
document.getElementById("answer").value = ids.reduce((count,id,index) => {
const { value } = document.getElementById(id);
return count + (parseFloat(value) || 0) * factors[index];
}, 0);
An alternative you can do is use a default parameter for your function.
Your calculate would look something like this:
Calculate(aaa=0, bbb, ccc) {
And this question covers how to pass html elements as parameters for functions.
Instead of using an if/else construct you can rely on the falsy value of an empty string.
Therefore you can initialize all your variables like this:
var aaa = document.getElementById('aaa').value || '0';
More information on falsy values can be found on the MDN.

getElementById not working - not returning anything at all

What the code is supposed to do:
Get user input (amount of car loan)
Have user click on button
Spit out monthly car pmt
Here is the code:
<script type="text/javascript">
var myObject = {
myFunction: function(){
return document.getElementById("carDebt");
},
h: function(){
var carLoan=myFunction();
var RATE12 = 0.005;
var TIMERATE = 0.25862780376;
return Math.round((carLoan * RATE12) / TIMERATE);
}
writeIt: function(){
var g = myObject.h();
var xyz = g;
var abc = 2;
var efg = 3;
var somearray = [xyz,abc,efg];
var z = 0;
for (i=0; i<somearray.length; i++) {
z += somearray[i];
};
document.getElementById("result").innerHTML=z;
}
};
</script>
<body>
<form>
Amt Due on Car Loan: <input type="number" id="carDebt">
</form>
<form>
<input type="button" onclick="myObject.writeIt()" value="Click here when done" id="button1">
</form>
<p id="result">Results Here</p>
</body>
I am not getting anything, as in, not even NaN or undefined. I am probably missing something obvious but I have tried a thousand different ways!
This line might be the culprit:
var carLoan=myFunction();
Try referencing the object it's under instead:
var carLoan = myObject.myFunction();
Furthermore, that function is returning the DOM element rather than the value of the DOM element. You'll probably want to edit the function to return the value:
myFunction: function(){
return document.getElementById("carDebt").value;
}
I also noticed that you have what appears to be too many tags. Do you mean to have two "forms"?
Seems the answers are in already putting together the above, ie fix typo, get value not element, have a "result" element to output to. I also added "this" to the myFunction call.
My version:
<script type="text/javascript">
var myObject =
{
myFunction: function()
{
return document.getElementById("carDebt").value;
},
h: function()
{
var carLoan = this.myFunction();
var RATE12 = 0.005;
var TIMERATE = 0.25862780376;
return Math.round((carLoan * RATE12) / TIMERATE);
},
writeIt: function()
{
var g = myObject.h();
var xyz = g;
var abc = 2;
var efg = 3;
var somearray = [xyz,abc,efg];
var z = 0;
for(i=0; i<somearray.length; i++)
{
z += somearray[i];
};
document.getElementById("result").innerHTML=z;
}
};
</script>
</head>
<body>
<form> Amt Due on Car Loan: <input type="number" id="carDebt"> </form>
<form> <input type="button" onclick="myObject.writeIt()" value="Click here when done" id="button1"> </form>
<div><p id="result"></p></div>
</body>

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Categories

Resources