oninput and onchange not working because of bad coding - javascript

My code is here. Below is the HTML:
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsVoltage()" onchange="EqualsVoltage()"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsCurrent()" onchange="EqualsCurrent()"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsResistance()" onchange="EqualsResistance()"> </p>
<script language="Javascript" type="text/javascript" src="EandM.js"></script>
</body>
</html>
Here is the Javascript:
//Electricity and Magnetism Stuff
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputVoltage").value = (Current * Resistance);
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputResistance").value = (Voltage / Current);
}
I want my calculator to react to both oninput and onchange events when I change a value in the text field.
I've been able to make a converter that converts kilometers to miles when oninput and onchange were functioning; however, I can't figure this out.
When I enter data in the field, it doesn't change the other values. Please help!

The problem: when user edit e.g. voltage in input then calculations at the same time change that input value (the input values and calculated values are usually different). Solution: show output calculations in separate place - not as input values. When you use oninput you don't need to use onchange.
function calc() {
let c = inputCurrent.value;
let r = inputResistance.value;
let v = inputVoltage.value;
msg.innerHTML = `voltage: ${ c*r } <br>`
+ `current: ${ v/r } <br>`
+ `resistance: ${ v/c } <br>`;
}
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="calc()">
</p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="calc()">
</p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="calc()">
</p>
Calculations:
<div id="msg"></div>

This works. Should have been checking the other text boxes not the current one. It will keep changing the fields as the user increases or decreases the value.
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<head>
<script type="text/javascript">
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Resistance != "0" && Current != "0" ){
document.getElementById("inputVoltage").value = (Current * Resistance);
}
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Resistance != "0" ){
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Current != "0" ){
document.getElementById("inputResistance").value = (Voltage / Current);
}
}
</script>
</head>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsResistance(); EqualsCurrent()" value="0"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsVoltage(); EqualsResistance()" value="0"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsCurrent();EqualsVoltage()" value="0"> </p>
</body>
</html>

There is already a great answer you can take, but I wanted to provide you an alternative. It's up to you which one fits better to your needs.
This solution provides an alternative for the user to decide when to calculate the values. This can avoid unexpected values as Infinity, 0, etc..
For this, you could give a button to every element in order to let the user click the one he wants the result for. This will update the value to the input box where he presses the button. The button would look like this:
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance"><!-- Add this to every input -->
Calc
</button>
</p>
And your JavaScript code will look like this:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
I hope this gives you another way to achieve what you want.
Here is a fiddle of what I am talking about:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number">
<button id="calcVoltage">
Calc
</button></p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number">
<button id="calcCurrent">
Calc
</button></p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance">
Calc
</button></p>

I would recommend using onkeyup instead of onchange and oninput. [edit] Wont work with the buttons, however.
I'm guessing the workflow is "When I enter something two number fields, the third one is calculated".
But what happens then if all three text fields are filled in?
If you filled in voltage, current, and resistance, and then change voltage again, should current or resistance change?
You need to think about workflow before you do any coding, and that's why the code is wrong.

Related

Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>

How to subtract X hours to a time field

I would like to output in a div the result of a math calculation (subtract). In the specific I have a form with a <input type="time" id="time" name="time"> that let user pick up a time. I would like to display in another div the result of the chosen time - 3 Hours.
So if time chosen is 13:00 I would like to output in the div with class result-1 10:00.
How can I achieve this in JS?
<form action="/action_page.php">
<label>Time:</label>
<input type="time" id="time" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result</div>
</div>
What I tried is to replicate what explained here but without result?
When you read data from the <input> element, the math library cannot be used directly because it reads data of type String. So I developed two different solutions that exhibit two different behaviours.
Behaviour-1
The following solution extracts the selected time value based on a time stored in the secondTime array.
const time1 = document.getElementById('time1');
let result = document.getElementById('result');
// If you want to calculate the difference to the fixed time point,
// change the contents of the secondTime array.
let firstTime = []; secondTime = ["03", "00"]
// Function that prints the time difference to the DOM
function calculate() {
if(firstTime.length != 0) {
var hours = firstTime[0] - secondTime[0];
var minutes = firstTime[1] - secondTime[1];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours}:${minutes}`);
}
}
// Event fired when <input> element changes
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
Behaviour-2
In the solution below, the value in the <input> element is parsed using the String.prototype.split() method and the time difference is calculated using the calculate() method. Edit the calculate() method for more accurate calculation.
const time1 = document.getElementById('time1');
const time2 = document.getElementById('time2');
let result = document.getElementById('result');
let firstTime = [], secondTime = [];
function calculate() {
if(firstTime.length != 0 && secondTime.length != 0) {
var hours = secondTime[0] - firstTime[0];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours} Hours`);
}
}
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
time2.onchange = function() {
secondTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
<label>Second Time:</label>
<input type="time" id="time2" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
First you should convert string time to integers then you can subtract.
<html>
<script>
function subTime(t,x) {
var t1 = t.split(':');
var x1 = x.split(':');
var tx0 =parseInt(t1[0])- parseInt(x[0]);
var tx1 =parseInt(t1[1])- parseInt(x[1]);
if(tx1<0){tx1+=60;tx0--;}
if(tx0<0){tx0+=12}
if(tx0<10){tx0="0"+tx0}
if(tx1<10){tx1="0"+tx1}
return tx0+":"+tx1;
}
function showTime(e){
var x = "3"+"00";
document.getElementById('res').innerText = subTime(e.target.value, x)
}
</script>
<body>
<input type="time" id="time" onChange='showTime(event);'/>
<div id='res'></div>
</body>
</html>

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Want to output a visual price

ok, I've spent the past 5 hours trying to codge together a small javascript code for a website.
Basically the widths are set values of 2 or 4 (which the user will use a simple drop-down option).
Length can be anything from 1 to 60.
The price will be a fixed price, so can just be hidden out of the way.
Now this is where I start to go South with the situation, I'm having problems spitting the result out into a div area on the page, this is what I have so far;
<script type="text/javascript">
function only_numbers(value){
var check_this = value;
var expression = /^\d*\.*\d*$/;
if(expression.test(check_this)){ return true; }
else{ return false; }
}
function calculate(){
var lengthVal = document.mult.lengthVal.value;
var heightVal = document.mult.heightVal.value;
var priceVal = document.mult.priceVal.value
var showValue = 0;
if(only_numbers(lengthVal) && only_numbers(heightVal) && only_numbers(priceVal)){
var showValue = ((lengthVal * heightVal) * 1.25) * priceVal;
// showValue = Math.round(showValue * 100) / 100;
document.getElementById('showValue').innerHTML = "showValue";
}else{
alert("Please enter only numerical values.");
}
}
</script>
</head>
<body>
<form name="mult">
Length: <input type="text" name="lengthVal" /> <br />
Height: <input type="text" name="heightVal" /> <br />
Price: <input type="text" name="priceVal" /> <br />
<input type="button" value="Calculate" onClick="calculate()" />
</form>
<div id="showValue"></div>
I know I've not sorted the price out to be hidden and is just an open variable atm, please guys, any help would be great.
document.getElementById('showValue').innerHTML = "showValue";
You probably want to write your variable value in there, not the string "showValue". So you should be using:
document.getElementById('showValue').innerHTML = showValue;

Categories

Resources