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;
}
}
Related
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 am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?
I'm trying to make a pen which incorporates the javascript exercises I'm learning. Here is the Pen: https://codepen.io/ychalfari/pen/JVYoNW
In this specific case I'm trying to accept an array from an input and run a function which sums the array when you click the button, and the result should show underneath.
When I click the button I either get an Error: "Bad Path /boomboom/index.html"
or nothing happens the page just kind of reloads and it takes me to the top of the page.
The HTML
<form id="sum-arr-form">
<div class="form-wrap" >
<label for="arr-to-sum"> Enter an Array to sum: <input id="arr-to-sum" class ="med-input" type="text" value = "">
<button class="btn1" onclick ="sumOfArray()">submit</div> </form>
<p>Result: <span id="demo"></span></p>
The Javascript
let inputArr = document.getElementById('arr-to-sum').value;
const add = (a,b) => a+b;
const sumOfArray = function() {
let sum = inputArr.reduce(add);
document.getElementById("demo").innerHTML = sum;};
You have some mistakes in your code.(button tag without type will trigger submit)
<button class="btn1" onclick ="sumOfArray()">submit
change this line to
<input type="button "class="btn1" onclick ="sumOfArray()" value="submit">
then get the value of input inside your sumOfArray function. (add the below 2 lines in your sumOfArray function) (waynelpu's answer above)
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);
The value get from input is string, if you want to process it as array you need to convert to correct type in js, try
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);
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>
var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?