Im trying to make a a simple form to calculate my client's services. I want to make a function that adds up the services' values and show them right away without clicking in the button. I have no idea where I'm wrong.
<p>In total: <span id="number"></span></p>
<script>
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z.value;
z.oninput = function() {
x.innerHTML = this.value;
}
</script>
Can you explain why it doesnt work? smh
Your script is running immediately and once only. You need to introduce an event that occurs each time you change the value of an input.
<p>In total: <span id="number"></span></p>
<input id="kilom" onchange=calculateTotal()>
<input id="myRange1" onchange=calculateTotal()>
<input id="myRange2" onchange=calculateTotal()>
<script>
function calculateTotal() {
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z;
}
</script>
function calculateTotal() {
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z;
}
<p>In total: <span id="number"></span></p>
<input id="kilom" onchange=calculateTotal()>
<input id="myRange1" onchange=calculateTotal()>
<input id="myRange2" onchange=calculateTotal()>
The variable z is not an input element. It is a number. So you cannot access .value or .oninput on that variable.
So in that regard. This..
x.innerHTML = z.value;
Should be..
x.innerHTML = z;
And I guess you want the value in the x tag to update in realtime? You need to add event listeners to all the input elements you use to calculate the z variable.
So that means the following code..
z.oninput = function() {
x.innerHTML = this.value;
}
can be rewritten as..
function calculateZ() {
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
x.textContent = z; // x.innerHTML = z; works as well, but is less safe.
}
// Triggers when changing the value in the kilom, myRange1 and myRange2 input tags
document.getElementById("kilom").addEventListener('change', calculateZ);
document.getElementById("myRange1").addEventListener('change', calculateZ);
document.getElementById("myRange2").addEventListener('change', calculateZ);
Related
I have two text input fields in html form and need to add the field's value when add button is clicked.
I have used parseFloat function but they seem to be concatenated instead of addition.
<input type="text" id="x"/>
<input type="text" id="y"/>
<button id="add">ADD</button>
<h1 id="displayResult"></h1>
<script>
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
x = parseFloat(x);
y = parseFloat(y);
add.addEventListener('click', ()=>{
displayResult.innerHTML = x.value + y.value
})
</script>
You just need to parse the value not the element
x = parseFloat(x);// x here not value but the element
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
add.addEventListener('click', function() {
displayResult.innerHTML = parseFloat(x.value) +parseFloat(y.value)
})
<input type="text" id="x" />
<input type="text" id="y" />
<button id="add">ADD</button>
<h1 id="displayResult"></h1>
you need to get value from x & y first before using parseFloat
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
add.addEventListener("click", function () {
x = parseFloat(x.value); // here
y = parseFloat(y.value); // here
displayResult.innerHTML = x + y;
});
function multiplicacion() {
var x = document.getElementById("v1").value;
var y = document.getElementById("v2").value;
var z = (x * y)
document.getElementById("salida").innerHTML = z
}
function division() {
var x = document.getElementById("v1").value;
var y = document.getElementById("v2").value;
var z = (x / y)
document.getElementById("salida").innerHTML = z
}
function suma() {
var x = parseInt(document.getElementById("v1").value);
var y = parseInt(document.getElementById("v2").value);
var z
z = x + y
document.getElementById("salida").innerHTML = z
}
function resta() {
var x = parseInt(document.getElementById("v1").value);
var y = parseInt(document.getElementById("v2").value);
var z
z = x - y
document.getElementById("salida").innerHTML = z
}
function PulsarTecla(event){
tecla = event.keyCode;
if(tecla == 189){
resta
}
}
window.onkeydown=PulsarTecla;
<html>
<head></head>
<body>
<div align = "center">
<font size = "5" id = "salida"> 0 </font>
<input type="text" name="v1" id="v1">
<input type="text" name="v2" id="v2"><br><br>
<button id="multiplicacion" onclick="multiplicacion()" class="button1">X</button>
<button id="division" onclick="division()" class="button3">/</button><br><br>
<button id="suma" onclick="suma()" class="suma">+</button>
<button id="resta" onclick="resta()" class="resta">-</button>
</div>
</body>
</html>
the problem is that I try to execute the "resta" function with the slash but it dont works, it only works with the buttons, I´ve only try this with the "resta" function
First I try to execute an alert with the slash and it works but no with the function
There are missing brackets in the function PulsarTecla. There is an identifier of another function resta but no brackets so this function isn't actually called.
This code should work:
function PulsarTecla(event){
tecla = event.keyCode;
if(tecla == 189){
resta()
}
}
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);
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>
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