How do i make text = integers - javascript

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

Related

JS. How do I create a regex pattern by concatenation with variables

I am not able to fix the following:
<html>
<head>
<title>Test</title>
<script>
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('/^[A-z]et_[' + s + ']_\\d/');
// NOTE I get the following, is that how it should be?
// window.alert(pattern); => /\/^[A-z]et_[0]_\d\//
// NOTE: I checked that it works fine for a single digit case, say:
// var pattern = new RegExp(/^[A-z]et_[3]_\d/);
var newarr = arr.filter(elt => pattern.test(elt));
document.getElementById("demo").innerHTML = newarr;
}}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
I see many similar questions, but I have not been able to find out how to fix my code. It should be possible, shouldn't it?
EDIT
the following is what I need:
<html>
<head>
<title>Test</title>
<script>
var newarr = [];
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('^[A-z]et_' + s + '_\\d'); // NOTE: not /
var lnewarr = arr.filter(elt => pattern.test(elt));
if(typeof lnewarr !== 'undefined' && lnewarr.length > 0){newarr.push(lnewarr)};
}
document.getElementById("demo").innerHTML = newarr;
}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
(sorry if my post is mostly code. Hope it may helps somebody out there.)
Instead of for loop you can use a .join like this:
var pattern = new RegExp('^[A-Za-z]et_[' + N.join('') + ']_\\d');
//=> /^[A-Za-z]et_[0123456789]_\d/
This works for the case when you have singe character values in your array N.
For generic use you can use this expression:
var pattern = new RegExp('^[A-Za-z]et_(?:' + N.join('|') + ')_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/
Using a for loop you can do this:
var N = [0,1,2,3,4,5,6,7,8,9];
var str='(?:';
for (var s in N)
str += s + '|';
str = str.replace(/\|$/, ')');
var pattern = new RegExp('^[A-Za-z]et_' + str + '_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

textbox calculator with parsing function to arithmetic function

What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);

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>

struggling with creating asterisks in Javascript

I've been struggling with this for some time now. What I wanted to create is to output a triangle of asterisks based on user's input. Let say user entered size 5, it would look something like this:
*
**
***
****
*****
My HTML looks like:
<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>
<pre id="output">
</pre>
In my Javascript, I have:
function draw()
{
var size = customJS.get ( "size" ); //I have a custom library where it get the Id from HTML
var theTriangle = makeTriangle( size.value ); //sending in the size
customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}
function makeTriangle( theSize )
{
var allLines = ""; // an empty string to hold the entire triangle
for ( var i = 0; i <= size; i++) // this loop size times
{
var oneLine = createLine ( i <= size ); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine ( length )
{
var aLine = ""; // an empty string to hold the contents of this one line
for ( var j = 0; j <= i; j++ ) //this loop length times
{
aLine += '*';
}
return aLine + "<br>";
}
anyone have any tip on how I go about this? thank you so much!
Newlines in HTML normally display as spaces, but you want them to show as newlines. The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag:
customJS.set ("output", "<pre>" + theTriangle + "</pre>");
Also, you're calling createLine like this:
var oneLine = createLine ( i <= size );
i <= size yields a boolean (true or false) rather than a number. You probably mean to just pass it i:
var oneLine = createLine ( i );
Additionally, you're setting size like this:
var size = customJS.get = ( "size" );
You probably want to drop the second equals, since as is, it sets the variable size to the string "size".
And finally, you've got a few variables wrong: in makeTriangle, you're looping size times, but size is undefined; you probably meant theSize. In createLine, you're looping i times, but i is undefined; you probably meant length.
With all that, it works.
There were several bugs in your code. For example using theSize instead size as parameter in the function makeTriangle(), using i instead of length in the createLine() function in the for loop condition.
Another one was:
use
return aLine + "<br/>";
instead of
return aLine + "\n";
The working solution for your code can be found in this jsFiddle: http://jsfiddle.net/uwe_guenther/wavDH/
And below is a copy of the fiddle:
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Size:
<input type="text" id="sizeTextField">
<input id='drawButton' type="button" value="Draw">
<div id='output'></div>
</p>
<script src='main.js'></script>
</body>
</html>
main.js
(function (document) {
var drawButton = document.getElementById('drawButton'),
sizeTextField = document.getElementById('sizeTextField'),
output = document.getElementById('output');
function makeTriangle(size) {
var allLines = '';
for (var i = 0; i <= size; i++) {
var oneLine = createLine(i); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 0; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
drawButton.onclick = function () {
output.innerHTML = makeTriangle(sizeTextField.value);
};
})(document);
You can leverage some JavaScript tricks to make the code a bit more terse:
<div style="text-align: center">
<label>Size:
<input type="text" id="size" value="5">
</label> <pre id='output'></pre>
</div>
<script>
var size = document.getElementById('size'),
output = document.getElementById('output');
function update() {
var width = +size.value, // Coerce to integer.
upsideDown = width < 0, // Check if negative.
width = Math.abs(width), // Ensure positive.
treeArray = Array(width).join('0').split('0') // Create an array of 0s "width" long.
.map(function(zero, level) { // Visit each one, giving us the chance to change it.
return Array(2 + level).join('*'); // Create a string of *s.
});
upsideDown && treeArray.reverse(); // If width was negative, stand the tree on its head.
output.innerHTML = treeArray.join('\n'); // Join it all together, and output it!
}
size.onkeyup = update;
update();
size.focus();
</script>
http://jsfiddle.net/mhtKY/4/

Categories

Resources