Multiple input events vanilla JS - javascript

Struggling to get all my input fields to work as intended.
The first field is working as it should but i want the phone input to change the phone_field to change as well.
How do i go around making this work with multiple fields?
<div class="formBox">
<label for="full_name">Fullt navn</label>
<input name="name" type="text" id="fullname" />
</div>
<div class="formBox">
<label for="phone">Tlf:</label>
<input name="phone" type="text" id="phone" />
</div>
<div class="formBox">
<label for="email">Epost:</label>
<input name="email" type="text" id="email" />
</div>
<div>
<h3 id="full_name_field">Ola Normann</h3>
</div>
<p id="phone_field">+47 123 12 123</p>
const input = document.querySelector('input');
const name = document.getElementById('full_name_field');
input.addEventListener('input', updateValue);
function updateValue(e) {
name.textContent = e.target.value;
}

You could have a function that updates phone_field and fires when a key is pressed in phone:
HTML:
<input name="phone" type="text" id="phone" onkeydown="updatePhoneField"/>
JS:
function updatePhoneField() {
phoneVal = document.getElementById("phone").value;
document.getElementById("phone_field").innerHTML = phoneVal;
}

Found a solution that works ( for now ) probably not ideal and not the best way to do it but!
const input1 = document.getElementById("fullname");
const output1 = document.getElementById("full_name_field");
document.getElementById('fullname').onkeyup = function () {
"use strict";
document.getElementById('full_name_field').textContent = this.value}

Related

How to get an span from its textnode or text content?

I have a form with 3 fields:
<form id="book-form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" placeholder="Enter a title">
</div>
<div class="form-group">
<label for="author">Author</label>
<input type="text" name="author" class="form-control" placeholder="Enter the author of the book">
</div>
<div class="form-group">
<label for="isbn">ISBN#</label>
<input type="text" name="isbn" class="form-control" placeholder="Enter the book isbn">
</div>
<button type="submit" class="btn btn-primary btn-block">Add Book to store</button>
</form>
Here are I am retrieving the value of these fields that I will insert in their respective span in the html.
const title = document.getElementsByName('title')[0].value
const author = document.getElementsByName('author')[0].value
const isbn = document.getElementsByName('isbn')[0].value
Now I have three span tags where the value of these form fields are suppose to be inserted.
<span class="title">// the value of title</span>
<span class="author">// the value of author</span>
<span class="isbn">// the value of isbn</span>
Now I have a function that checks if the retrieve from the fields of the form is not empty(null) if that is the case I want to remove the span that is was suppose to be in the dom.
function insertMe(fieldValue) {
if (fieldValue === "") {
// How to remove the span that it was suppose to go
} else {
return fieldValue
}
}
It's not clear how you're calling insertMe, and the name of that function is misleading because you're only removing elements, not adding them.
I'd approach it this way.
When the button is clicked/onSubmit call the function and use querySelectorAll to target all the inputs by class. Iterate over them and if the value is an empty string remove the span whose class matches the name of the input, otherwise set the text content of the span to the input value.
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
const inputs = document.querySelectorAll('.form-control');
inputs.forEach(({ name, value }) => {
const el = document.querySelector(`span.${name}`);
if (el && !value) {
el.remove();
} else {
el.textContent = value;
}
});
}
<input type="text" class="form-control" name="title" placeholder="Enter a title">
<input type="text" class="form-control" name="author" placeholder="Enter an author">
<input type="text" class="form-control" name="isbn" placeholder="Enter an ISBN number">
<button>Click</button>
<br/><br/>
<span class="title">Title</span><br/>
<span class="author">Author</span><br/>
<span class="isbn">ISBN</span><br/>

Combine two textbox value into other textbox in lowercase with dash

I have two text type inputs. I want to convert them into one textbox(Lowercase with dash) while typing just like below.
<input type="text" name="first">
<input type="text" name="last">
I want combine this two text box into another textbox
Example: Nikhil Patel to nikhil-patel
I am trying to combine below inputs but can't.
function conv(){
var title, author;
title = document.getElementById("title").value;
author = document.getElementById("author").value;
/*converting to LowerCase*/
title = String.toLowerCase(title);
author = String.toLowerCase(author);
var out = title + "-" + author;
document.getElementById("output").value = output;
}
<div class="form-group">
<label>Title :</label>
<input class="form-control" type="text" name="title" id="title" />
</div>
<div class="form-group">
<label>Author :</label>
<input class="form-control" type="text" name="author" id="author" />
</div>
<div class="form-group">
<label>Output :</label>
<input class="form-control" type="text" name="output" id="output"/>
</div>
Output is not printing automatically
Try This if you want like this...
var input = $('[name="first"],[name="last"]'),
input1 = $('[name="first"]'),
input2 = $('[name="last"]'),
input3 = $('[name="final"]');
input.change(function () {
input3.val(input1.val() + ' - ' + input2.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="first" id="1" value="">
<input type="text" name="last" id="2" value="">
<input type="text" name="final" id="3" value="" readonly>
<HTML>
<HEAD>
<SCRIPT>
function conv(){
var first, second;
first = document.getElementById("first").value;
second = document.getElementById("second").value;
/*converting to LowerCase*/
first = String.toLowerCase(first);
second = String.toLowerCase(second);
var out = first + "-" + second;
document.getElementById("out").value = out;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="text" name = "first" id="first" onkeyup = 'conv()'/>
<input type="text" name = "second" id ="second" onkeyup = 'conv()'/>
<input type="text" name = "out" id="out"/>
</BODY>
</HTML>
this is just a sample with 3 text boxes where
first two boxes will be for input
and third will auto populate using the javascript
I hope it'll help you. All is did was to add extra id's.

Computing using functions and arrays / Output error: Not a Number

Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>

How to check if input name is inside an array in Jquery?

I want to know how I can check if input name is equal to name inside an array.
I have multiple inputs like below code:
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
And I have an array Like this:
var array = ['last_name', 'email'];
I want to add class to div, that wrap the input his name inside the array.
I don't want to use 2 loops.
You can use the following code:
var inputs = $("input");
var array = ['last_name', 'email'];
inputs.each(function(){
if(array.indexOf($(this).attr("name")) >= 0){
alert($(this).attr("name")+" exists");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
The HTML to the code is same as used by you in your question, I have added a bit of JQuery, that is simple to understand.
I hope it was helpful.
check output in browser console:
$(document).ready(function() {
var array = ['last_name', 'email', 'dsfdsfds'];
array.forEach(function(element) {
var x = document.getElementsByName(element);
console.log(x);
});
});
//check output in browser console
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
there is your solution :)
$(document).ready(function() {
var array = ['last_name', 'email'];
var inputs = $("div[class='inputMain']").find("input");
array.forEach(function(name) {
inputs.each(function (x){
if (inputs[x].name === name) {
inputs[x].parentNode.classList.add("myClass")
}
});
});
console.log(inputs.prevObject);
});
https://jsfiddle.net/12es37ko/62/
you can check result into browser console :)

Calculate change to be given to customer on POS javascript

Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.
The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787
Here is the code that I'm using.
function sum() {
var og_total = document.getElementById('og_cart_total').value;
var og_tendered = document.getElementById('og_cash_tendered').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = '£';
if (!isNaN(og_change)) {
document.getElementById('og_change_given').value = og_symbol + og_change;
}
}
<input type="hidden" id="og_cart_total" value="19.99" onkeyup="sum();" />
<div class="control-group">
<label class="control-label" for="og_cash_tendered">Tendered:</label>
<div class="controls">
<input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="og_change_given">Change:</label>
<div class="controls">
<input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />
</div>
</div>
there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.
function sum() {
var og_total = document.getElementById('txt1').value;
var og_tendered = document.getElementById('txt2').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = "£";
if (!isNaN(og_change)) {
document.getElementById('og_change_text').value = og_symbol + og_change;
}
}
<input type="text" id="txt1" value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />

Categories