I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>
Related
I want to assign the values - value and value 2 into the DATAID and DEPNUM when clicking the drop-down and using onchange() function in the following HTML FORM
The places that are being assigned are parts of a readonly field which contains string.
My goal is to create a readonly string which will contain the values that I've chosen from the dropdown fields, all combined in 1 string and separated by underscore.
I've been trying to use onChange method "myFunction()"
<input name="_1_1_2_1" tabindex="-1" class="valueEditable" id="myInput" onchange="myFunction()" type="text" size="32" value="...">
which will look like :
function myFunction()
{
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = x;
}
eventually I run it on the paragraph :
<p id="demo" value="DATAID_DOCTYPE_DEPNUM_NTA">DATAID_DOCTYPE_DEPNUM_NTA</p>
The problem is that the value at is not changing instant as i change value2 or value.
You can bind two event-listener for both two input fields and updated the readonly textfield value by below approach.
$(document).ready(function(){
$('#field1').keyup(function() {
updatedReadonlyFieldVal($(this), 0);
});
$('#field2').keyup(function() {
updatedReadonlyFieldVal($(this), 2);
});
function updatedReadonlyFieldVal(elem, index) {
let val = elem.val();
let destVal = $('#destination').val();
let splittedDestVal = destVal.split('_');
splittedDestVal[index] = val;
$('#destination').val(splittedDestVal.join('_'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input value="DATAID_DOCTYPE_DATANUM" readonly id="destination">
Please don't hesitate to let me know if you have any query.
I want to add two zeros to any number entered in a textbox when submitted.
For instance, if i enter 34 in a textbox and click on submit, it should be saved as 3400.
Could this be done on the fly too?
Depends on what you want to do after the submit. Especially: Do you want to interpret this as a number and simply multiply by 100 (34 * 100) or do you want to simply append something to the value? ("34" + "00")?
In the first case you would do this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = parseInt(input.value) * 100;
}
</script>
In the second case this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = input.value.toString() + '00';
}
</script>
A bit vague, but it sounds like you're looking for something like the following.
// Gather each element from the HTML, so you can access its input or update its display:
const input = document.getElementById('numberInput');
const button = document.getElementById('submit');
const display1 = document.getElementById('display1');
const display2 = document.getElementById('display2');
// Add a click event to the button, which gathers the text field value, ensures it's a number, and updates the display as requested:
button.addEventListener('click',() => {
const value = input.value;
// This if statement ensures that only numbers will be suffixed with be suffixed with two zeros:
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
// Update the display span's contents as requested. There are many ways of doing this. Here are a few;
// Here I'm taking the submitted value, and nesting it inside a string, alongside the two zeros. In cases of Infinity or .100, the result will still be the input suffixed with two zeros:
display1.innerHTML = `${value}00`;
// This method, on the other hand, will simply move the decimal to columns:
display2.innerHTML = value * 100;
});
<p>
Display 1: <span id="display1"></span>
</p>
<p>
Display 2: <span id="display2"></span>
</p>
<input type="text" id="numberInput">
<button id="submit">Submit</button>
You could always set an event listener that changes the number on exit of the form element, so something like this:
document.addEventListener('DOMContentLoaded', watchNums);
function watchNums() {
document.removeEventListener('DOMContentLoaded', watchNums);
Array.from(document.getElementsByClassName('number')).map(
number => {
number.addEventListener('blur', _ => {
number.value = parseInt(number.value) * 100;
})
}
)
}
<body>
<form action="/endpoint.htm" method="POST">
<input type="number" name="number-input" class="number">
<input type="number" name="other-number-input" class="number">
<button type="submit">Submit Numbers</button>
</form>
</body>
I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)
I have a very simple form in HTML:
<form>
Number: <input id="form" type="text" name="Number"/>
</form>
Then I have this JavaScript:
var n = document.getElementById("form").value;
//calculations with n
//later, it outputs another variable (steps) that comes from that value of n
I want it to work out so that whenever the user types anything into the textbox, it does all of the JavaScript code and outputs the steps without having any submit button or anything like that. So if the user is going to type 123, for example, when they type 1, it will output steps when calculated for 1, then when they type the 2, it will output steps when calculated for 12, then when the type the 3, it will output steps when calculated for 123.
Use onInput event:
<input id="form" type="text" onInput="yourFunction();" />
JavaScript:
function yourFunction() {
var n = document.getElementById("form").value;
}
W3Schools documentation
Example:
function yourFunction() {
var n = document.getElementById("form").value;
document.getElementById("output").innerHTML = n;
}
Input: <input id="form" type="text" name="Number" onInput="yourFunction();" />
<div id="output"></div>
Register an onkeypress event handler on the input element and let that handler do the calculation. Btw you don't need the form container.
You need to trap the input event, and run your code in response
;(function(){
"use strict";
// make sure the DOM is available
document.addEventListener('DOMContentLoaded',function(){
// function that does the work
var calculateResult = function(event){
o.value = n.valueAsNumber.toString(2);
};
// select the DOM elements
var n = document.getElementById('n');
var o = document.getElementById('o');
// attach your function to the input event
n.addEventListener('input',calculateResult);
});
})();
<form id="f">
Number: <input id="n" type="number" name="n"/>
</form>
Number As Binary:
<output form="f" for="n" id="o"></output>
I'm fairly new to javascript and have a question about how to get a value of an input field without submitting a form. I have the following small piece of code, which I'm using in combination with a realtime-validation script to validate the fields.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var NameValue = document.forms["FormName"]["nameValidation"].value;
</script>
</form>
I want the var NameValue to be the value of what you type into the input field so I can use it in the message which appears after the validation. When I change the value of the input field without submitting the form, the var NameValue is stil set to "HelloWorld". After doing some research I found out I could solve it using jQuery and it's function serialize(). Is there a way to do this without jQuery?
Without jQuery :
var value = document.getElementById('nameValidation').value;
The syntax you had would be usable to get an input by its name, not its id.
If what you want is to use this value when it changes, you can do that :
var nameValidationInput = document.getElementById('nameValidation');
function useValue() {
var NameValue = nameValidationInput.value;
// use it
alert(NameValue); // just to show the new value
}
nameValidationInput.onchange = useValue;
nameValidationInput.onblur = useValue;
Your code works. It assign value of your input field to var NameValue. What you explained and what JQuery serialize does are two different things.
Everything you need is to assign your code to right event:
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" onchange="myFunction()"/>
</form>
<script type="text/javascript">
function myFunction(){
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
​see the JSFiddle.
use the onchange or onblur event to call this code:
var NameValue = document.forms["FormName"]["nameValidation"].value;
This way it will get activated when the cursor leaves the textbox
<input type="text" id="nameValidation" value="HelloWorld" onblur="changeVal();" />
<script type="text/javascript">
function changeVal() {
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
In your example, the variable only gets the value assigned to it at that moment in time. It does not update when the textbox updates. You need to trigger a function [onchange or onblur or keypress] and reset the variable to the new value.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var myTextbox = document.getElementById("nameValidation");
var nameValue = myTextbox.value;
myTextbox.onchange = function() {
nameValue = myTextbox.value;
};
</script>
</form>
You can let your client-side code respond to a change in the value of the textbox, like so:
$(document).ready(function(){
$("#nameValidation").on('change', function() {
var value = $("#nameValidation").value;
//do your work here
}
})