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>
Related
`
<input type="number" id="qty">
<input type="button" onclick="add()" value="Add">
<script>
function add(){
qty = document.getElementById('qty').value
if(qty>0){
var tot = qty*25
document.write(tot)
}else{
qty = ""
alert("no")
}
}
</script>
'qty=""' is the correct way as mentioned on google. but not working for me.
Try
document.getElementById("qty").value = "";
and cast qty to number in your if
if(Number(qty) > 0)
Values of inputs are always string , try this one in your condition :
if(Number(qty)>0){
...
}
Use this below code to clear the input
qty.value = "";
The reason why qty = '' isn't working is that you've assigned the string value of the input to that variable. Setting it to an empty string won't make the value of the input change - you need to explicitly change the element's value.
So, a few things first:
It's often useful to cache your elements first.
Remove the inline JS and replace it with addEventListener and attach it to the button element (a more modern approach).
Use a <button> element instead of an <input type="button">
Assign the total to an element's text content/innerText instead of document.write for various reasons.
Then when the handler is called coerce the string value of the input to a number, and use that in the condition. If the number is less than zero assign an empty string to the input value.
// Cache the elements
const qty = document.querySelector('#qty');
const result = document.querySelector('#result');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', add);
function add() {
// Coerce the input value to a number
const val = Number(qty.value);
if (val > 0) {
// Instead of `document.write` assign
// the total to the text content of an element
result.textContent = val * 25;
} else {
// Set the value of the qty element to
// an empty string
qty.value = '';
console.log('no');
}
}
#result { margin-top: 0.5em; }
<input type="number" id="qty">
<button type="button">Add</button>
<div id="result"></div>
if you want to check in time when you enter a value (as I understood from the question), you must have a listener on <input type=" number" id="qty"> and event
'input'. qty.addEventListener('input', (e)=>{ // .... make your validation })
I have this problem to solve
In this form a user types in a value. (Actually,
a scanner scans a number and virtually types it - without
sending extra keys like Enter)
I need to contantly check - while typing is going on - if the value in the input
box is a 8 digit number (starting with "4") and if it
is, fire the submit action.
I tried to log any changes. But the code below only logs changes after I leave the input box.
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" onChange="console.log(this.value);">
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
</form>
Is there a Javascript way to pass the value of the box to a function whenever a single letter is typed?
Note: While the form displays a "scan" button, the goal is to have that button automatically clicked as soon as 8 digits have been entered and been declared valid by a validator function.
It is generally not a good idea to use inline event handlers.
Actually, a scanner scans a number and virtually types it
So, as far as I understand you want to show the result of some scanning function that inputs values and check the input value. Looks like there's not really a need for a change handler. Here's a minimal reproducable example for a dummy scanning function. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function scan(i = 0) {
const inp = document.querySelector(`[name='boarding_id']`);
const showIt = document.querySelector(`#showIt`);
if (i < 1) {
inp.value = 4;
i += 1;
} else {
const nr = 1 + Math.floor(Math.random() * 9);
const currentValue = inp.value;
inp.value += nr;
}
if (i < 8) {
showIt.textContent = `Scanning ...`;
return setTimeout( () => scan(i + 1), 100)
}
showIt.textContent = `Done!`;
document.querySelector(`#scan`).removeAttribute(`disabled`);
}
function handle(evt)
{
if (evt.target.id === `scan`) {
evt.target.setAttribute(`disabled`, `disabled`);
return scan();
}
}
<input name="boarding_id" value="" width="600px" readonly>
<span id="showIt"></span>
<p><button id="scan">Scan</button></p>
const input = document.querySelector('input');
const demo_variable = document.getElementById('demo_variable');
input.addEventListener('input', updateValue);
function updateValue(e) {
demo_variable.textContent = e.target.value;
}
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" >
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
<p id="demo_variable"></p>
</form>
You can use the input event, which also triggers when editing happens without the keyboard (mouse drag/drop, context menu, other device...).
Use a regular expression to do the verification. You can access the form via the form property of the input element:
<input name="boarding_id" oninput="/^4\d{7}$/.test(this.value) && this.form.submit()">
It is however better practice to bind events not with HTML attributes, but with JS code. For that purpose give the form element an id attribute (like id="frm"), and then:
const form = document.getElementById("frm");
form.boarding_id.addEventListener("input", (e) => /^4\d{7}$/.test(e.target.value) && form.submit());
You can achieve this in multiple ways. I have shown one below
function myFunction() {
const userInput = document.getElementById("numberinput").value;
document.getElementById("displaynumber").innerHTML = "You typed: " + userInput;
}
function submtValue(value) {
const submitValue =document.getElementById("numberinput").value;
if(submitValue.length === 8) {
// do your validation
alert("Bingo..!!")
}
else {
alert("Minimum length required is 8")
}
}
<input type="number" id="numberinput" oninput="myFunction()">
<p id="displaynumber"></p>
<button type="submit" value="Submit" onclick="submtValue()">Submit</button>
You can add key event like onkeydown or onkeypress on input which will trigger everytime type inside input and once condition fulfilled submit form
I'm making site to make table game calculations easier. So, if simplify, I have a form like this:
<input id="x"/>
<input id="y"/>
And I want to collect data of this form in live time and process them like this immediately:
<span id="x-plus-y"/> in html and document.getElementById('x-plus-y').innerHTML = x*y in js
It's very simplified but I think you got the thought.
My question is how to process x+y immediately as the user enters the values into the input fields.
This is the simple approach you can go through. I have attached a keyup event listener on every input and then invoking the updateResult function which calculates the product and displays it within the result div.
HTML
Number 1 : <input type="number">
<br><br>
Number 2 : <input type="number">
<br><br>
<div id="result">
</div>
JS
const inputs = Array.from(document.querySelectorAll("input"));
const resultDiv = document.querySelector("div");
const numbers = [];
for(const input of inputs) {
input.addEventListener('keyup', updateResult);
}
function updateResult() {
let product = 1;
for(const input of inputs) {
product*= parseInt(input.value,10);
}
if(!isNaN(product)) {
resultDiv.innerHTML = "Product: " + product;
}
}
I have this code in HTML:
<input type="number" step="0.1" class="form-group">
I want the user to be able to enter a 3-digit decimal number like 1.234 but step needs to be 0.1 and it throws an error and prevents the form from submitting.
I've already tried step="0.100" but the result was the same.
I also need to validate other inputs so I can't use no validate in the <form> tag.
What needs to be done?
I'd write a small customized built-in custom element doing just that:
class MyInput extends HTMLInputElement {
constructor(step = 0.1, value = '') {
super();
this.type = 'number';
this.step = this.getAttribute('step') || step;
this.value = this.getAttribute('value') || value;
this.addEventListener('input', (e) => {
this.value = parseFloat(this.value) + 0.034;
})
}
}
customElements.define('my-input', MyInput, { extends: 'input' });
let input = new MyInput(0.1, 1);
document.body.appendChild(input);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />
This definitely needs some tweaking, e.g. if the user types in the input, but this should serve you well as a starting point.
One thought is you could remove the step attribute, disable the +/- slider buttons, and implement your own +/- buttons. Then, when a user clicks those buttons, a JavaScript function is called that retrieves the value in the input area, converts it to a number, and performs the desired step.
You might run into precision issues with using a step like 0.1. In the below snippet I just fixed the number of decimal places to two.
function stepUp(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num + step).toFixed(2);
}
function stepDown(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num - step).toFixed(2);
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<button onclick="stepDown(0.1)">-</button>
<input id="value" type="number" value="0.00">
<button onclick="stepUp(0.1)">+</button>
You can use novalidate and write your own validation in js for other form fields
<form novalidate>
<input type="number" step="0.1" class="form-group" >
<button>submit</button>
</form>
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>