I want to get input from user, multiply it by 1.3 for example and output to window instantly, like as user types function is executing and displaying in it in HTML instantly. How do it do it?
Here my code
function calc() {
amount = document.getElementById("amount").value;
num2 = 1.3;
document.getElementById("result").innerHTML = amount * num2;
return result;
}
<input id='amount', type="text" >
<button onclick="calc()"> Buy Now! </button>
<p> Result is: <br>
<span id = "result"> </span>
<input type="text"onkeyup="calc()">
First off, you got some invalid HTML:
What's that comma?
<input id='amount', type="text" >
Attributes don't need any separator — just put a space:
<input id='amount' type="text" >
Getting rid of pointless spaces, a cleaner HTML fragment follows:
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Now, let's try to list some options:
The keydown and keypress events won't work because they're fired before value changes.
The keyup event, as suggested #Dmitri Usanov, will work only partially: it is called when the key releases (not as soon as the text is updated) and if you e.g. paste by right-clicking then it won't fire.
The input is the solution. Note that it requires HTML5.
Working demo:
function calc() {
// Let's convert the input text to a number.
const amount = +document.getElementById("amount").value;
// The number to multiply by.
const num2 = 1.3;
// The number of decimal places we wish to truncate at.
const precision = 2;
const scale = 10 ** precision;
return Math.round(amount * num2 * scale) / scale;
}
window.addEventListener("load", () => {
const outputSpan = document.getElementById("result");
document.getElementById("amount").addEventListener("input", () => {
outputSpan.innerHTML = calc(this.value);
});
});
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Try this
function calc(isEsc) {
const num2 = 1.3;
let result = document.getElementById("result"),
amount = document.getElementById("amount");
if (isEsc) {
result.innerHTML = 0;
amount.value = '';
} else {
result.innerHTML = amount.value * num2;
}
}
document.onkeyup = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
calc(isEscape);
};
<input type="text" id="amount" />
<span id="result">0</span>
Related
How to enabled button, when the actual amount entered
lets say i have 100 minimum and 200 maximum
i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled
when user enters more than 200 do the same echo error
user has to enter 100 and above but not exceed maximum
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
var textBox = $('#Textfield').val();
if((textBox >= 100) || (textBox <= 200) ){
$('.disabledButton').prop("disabled", false);
} else {
$('#error').text('actual amount needed');
return false;
}
});
</script>
There's a number of reasons your code is not working:
.val() is always text, so you are (would be) comparing "15" with 100 and 200 and it would pass, convert to an integer
you start with the button disabled, then (assuming everything else is working ok) you enable it, but never disable it again if the value changes again
same for the #error text, you don't clear it when the value is valid
The main issue is:
if((textBox >= 100) || (textBox <= 200) ){
if the textbox value is greater than 100 OR it's less than 200, well, all values follow this rule: eg 1 is less than 200, so passes, 3000 is more than 100, so passes.
This should be
if((textBox >= 100) && (textBox <= 200) ){
Giving updated snippet:
$('#Textfield').keyup(function() {
var textBox = $('#Textfield').val() * 1;
if ((textBox >= 100) && (textBox <= 200)) {
$('.disabledButton').prop("disabled", false);
$('#error').text('ok');
} else {
$('.disabledButton').prop("disabled", true);
$('#error').text('actual amount needed');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
If you are using html 5, you don't need JavaScript. The best way to do this is to set this field to a number, like
<input type="number" min="100" max="200" placeholder="value in 100-200" id="Textfield" />
By setting min and max values, the form will not submit if the value in this field is not in that range
$('#Textfield').on('keyup',function(){
//every time a key is pressed we count the total number of characters in the field
var charLength = $(this).val().length;
//if they are equal to or above 100 and equal to or below 200 we disable the disabled button property else we disable the button again
if(charLength >= 100 && charLength <= 200){
$('.disabledButton').prop('disabled',false)
}else{
$('.disabledButton').prop('disabled',true)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
EDIT
Sorry, I guess I kinda just glossed over the question. Here's your working code))
<form>
<input type="text" />
<button type="submit" disabled>Submit</button>
<p id="error" style="color: red"></p>
</form>
<script>
const input = document.querySelector('input');
const button = document.querySelector('button');
const error = document.querySelector('#error');
const minVal = 100;
const maxVal = 200;
const setError = (current) => {
const message = `Please enter between ${minVal} and ${maxVal}. You entered ${current}`;
error.innerText = message;
error.style.display = 'block';
};
const hideError = () => {
error.style.display = 'none';
};
input.addEventListener('keyup', () => {
const enteredValue = parseInt(input.value, 10);
if (enteredValue >= minVal && enteredValue <= maxVal) {
button.disabled = false;
return hideError();
}
setError(enteredValue);
button.disabled = true;
});
</script>
previous edit: Edited to add dynamic error message
<form>
<input type="text" max="200" />
<button type="submit" disabled>Submit</button>
<p id="error" style="color: red"></p>
</form>
<script>
const input = document.querySelector('input');
const button = document.querySelector('button');
const error = document.querySelector('#error');
const minChars = 10;
const setError = (length) => {
const message = `Please enter ${minChars - length} more character(s).`;
error.innerText = message;
error.style.display = 'block';
};
const hideError = () => {
error.style.display = 'none';
};
input.addEventListener('keyup', () => {
const enteredLength = input.value.length;
if (enteredLength >= minChars) {
button.disabled = false;
return hideError();
}
setError(enteredLength);
button.disabled = true;
});
</script>
I have three fields that are calculated: coef, cost of materials, and manufacturing cost.
First, calculate its coef * cost of materials, result in manufacturing cost input.
The calculation of the total amount is the cost of materials * manufacturing cost, but I need the ability to change the amount of Manufacturing cost and get the total result
How to do this?
My code:
function sum(el) {
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let extraresultEl;
let result;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="sum(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
You need to apply a different function on mf cost input, because if you will use the same function, it will never let you alter the value, because its value also getting generated from the same function you write for above 2 values
if you need something else, pls feel free to comment
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
function sum(el) {
let extraresultEl;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
function canBeChnaged(el){
var coefVal = parseInt(coefEl.value);
var costofMatVal = parseInt(entrPriceEl.value);
var mfCostVal = parseInt(extraEl.value);
var finalSum = (coefVal * costofMatVal) + mfCostVal;
priceEl.value = finalSum.toFixed(2);
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="canBeChnaged(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
A more succinct way is to is to wrap everything into a <form> then listen for the input event. The input event will trigger a call to an event handler (in the example below it is function calc(e)) whenever the user enters data in a form control (in this case all <input>s of <form>). Use properties of HTML elements like type and step to control and validate user input. References to previously mentioned topics are located after the example below.
Details are commented in example below
// Register the <form>
const form = document.forms[0];
// Register all form controls of <form>
// In this case all <input> and <output>
const data = form.elements;
// Run function calc() if any valid user input is entered in <form>
form.oninput = calc;
// Pass the event
function calc(e) {
// Convert any valid user input of the <input>s into a real number
const c = parseFloat(data.cof.value);
const m = parseFloat(data.mat.value);
const l = parseFloat(data.lab.value);
// Reference the <output>
const s = data.sum;
// Realistic formula
const t = (c * m) + l;
// Display the value of output as the result of formula
s.value = t.toFixed(2);
}
:root,
input,
output {
font: 400 6vh/10vh Consolas;
}
label,
input,
output {
display: inline-block;
}
label {
width: 9ch;
}
input,
output {
height: 1.5ch;
width: 12ch;
text-align: right;
}
#cof {
width: 6ch;
text-align: center;
color: blue;
}
<form>
<label>Markup</label>
<input id="cof" type="number" value="2">
<br>
<label>Materials</label>
<input id='mat' type="number" value="0.00" step=".01">
<br>
<label>Labor</label>
<input id='lab' type="number" value='0.00' step=".01">
<hr>
<label>Total: </label>
<output id='sum'>0.00</output>
</form>
Reference
HTMLFormControlCollection
HTMLFormElement
<input> Element
I want first click to make the getNumberBtn to be getNumberBtnn
and the second one to get it back to getNumberBtn function.
When I click, the function run but doesn't change the onclick property
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn();
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn();
equation = equation + x;
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
When you assign the function to onclick, you are actually calling the function and thus creating an infinite recursive.
You can just assign the function name to onclick -
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
But I would suggest you use DOM event registration instead using addEventListener and removeEventListener-
var equation = 0;
var apply = document.getElementById("apply");
apply.addEventListener('click', getNumberBtn);
function getNumberBtn() {
apply.removeEventListener('click', getNumberBtn);
apply.addEventListener('click', getNumberBtnn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
apply.removeEventListener('click', getNumberBtnn);
apply.addEventListener('click', getNumberBtn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply">Apply</button>
</div>
You do not assign the event handler but the result of the function.
As I said in my comment, remove the () from the end of the function you assign.
Also you do not assign anything to x
However I suggest you do this instead:
Use eventListener
Use a function to decide which function to call
Have the list on functions in an object
Actually have different functions
let equation = 0;
const funcs = {
"btn": function(x) {
equation += x; // for example
console.log("btn", equation)
},
"btnn": function(x) {
equation *= x; // for example
console.log("btnn", equation)
}
}
document.getElementById("apply").addEventListener("click", function(e) {
const tgt = e.target;
const func = tgt.dataset.func
tgt.dataset.func = func === "btn" ? "btnn" : "btn"; // toggle the function
funcs[func](+document.getElementById("number").value); // call the chose function with a value
})
<div>
<input type="number" id="number" min="1" max="1000">
<button type="button" data-func="btn" id="apply">Apply</button>
</div>
Remove () from in front of function name while editing onclick property
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + x;
}
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.
Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<script>
var x = document.getElementById('x').innerHTML;
var y = document.getElementById('y').innerHTML;
var z = x + y;
var p = document.getElementById('p');
</script>
<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>
<br>
<p id="p"></p>
First attaching the click event to your button from the JS code using addEventListener will be better (avoid the inline-events), then put your code inside, you have to use .value insted of innerHTML to get the value of a textarea.
Note also that you should use double equals == when you want to compare two elements, and because we need to perform a math operations we should cast our values to numbers using Number() method.
Should be something like :
document.getElementById("calculate").addEventListener("click", function() {
var x = Number( document.getElementById('x').value );
var y = Number( document.getElementById('y').value );
var z = x + y;
var p = document.getElementById('p');
if (z == document.getElementById('z').value) {
p.innerText = "true";
} else {
p.innerText = "false";
}
});
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<button id="calculate">Calculate</button>
<br>
<p id="p"></p>
first of all, I suggest you to use input here instead of
Second thing is, I would suggest you to use function when you use 'onclick'
Here's the result:
<html>
<body>
<input type='number' placeholder='x: (input number please)' id="x" />
<input type='number' placeholder='y: (input number please)' id="y" />
<input type='number' placeholder='z: (input number please)' id="z" />
<br />
<button onclick="CheckByFormula()">Calculate</button>
<br />
<p>Check result: z=x+y ?</p>
<p id="p"></p>
<script type='text/javascript'>
function CheckByFormula(){
var x = parseInt(document.getElementById('x').value);
var y = parseInt(document.getElementById('y').value);
var z = x + y;
//alert('having these params:\n x='+x+' y='+y+' z='+z);
var p = document.getElementById('p');
z1 = parseInt(document.getElementById('z').value);
alert('z1='+z1+' z='+z);
if(z1 == z){
document.getElementById('p').innerHTML = 'true'
}
else {
document.getElementById('p').innerHTML = 'false';
}
}
</script>
</body>
</html>
https://jsfiddle.net/14pm7ypz/2/
I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}