Autofocus after <input> and again after all inputs - javascript

Creating a check for entered numbers on the right div with random numbers on the left div
I don't understand how to make sure that:
after entering smth in the first input, it must focus on the second and etc.
And how after all filled inputs, it must focus again on the first input
sorry for my english
do not offer jquery, please
'use strict';
let codeNum = document.querySelectorAll('.codeNumber'),
inputNum = document.querySelectorAll('input');
function randomCode() {
codeNum.forEach(function(item) {
item.textContent = randomInteger(0, 9);
})
function randomInteger(min, max) {
// получить случайное число от (min-0.5) до (max+0.5)
let rand = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(rand);
}
}
randomCode();
let new1 = [];
let new2 = [];
function checkInput() {
for (var i=0;i<codeNum.length;i++) {
new1[i] = codeNum[i].innerHTML;
new2[i] = inputNum[i].value;
}
if (JSON.stringify(new1)==JSON.stringify(new2)) {
randomCode();
}
console.log(JSON.stringify(new1));
console.log(JSON.stringify(new2));
}
for (var i=0;i<codeNum.length;i++) {
inputNum[i].addEventListener('input', checkInput)
}
#import url('https://fonts.googleapis.com/css?family=Raleway:200');
html, body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: space-around;
height: 100%;
background: #1D1F20;
}
.text {
width: 25px;
height: 47px;
border: 1px solid #a7a7a7;
border-radius: 4px;
background-color: #1D1F20;
outline: none;
font-size: 2.5rem;
font-family: 'Raleway';
text-align: center;
color: #fff;
vertical-align: middle;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */
-webkit-appearance: none;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}
span {
position: absolute;
top: 6%;
}
#box {
display: flex;
align-items: center;
justify-content: space-around;
width: 400px;
height: 200px;
color: white;
font-family: 'Raleway';
font-size: 2.5rem;
}
.gradient-border {
--borderWidth: 3px;
background: #1D1F20;
position: relative;
border-radius: var(--borderWidth);
}
.gradient-border:after {
content: '';
position: absolute;
top: calc(-1 * var(--borderWidth));
left: calc(-1 * var(--borderWidth));
height: calc(100% + var(--borderWidth) * 2);
width: calc(100% + var(--borderWidth) * 2);
background: linear-gradient(60deg, #f79533, #f37055, #ef4e7b, #a166ab, #5073b8, #1098ad, #07b39b, #6fba82);
border-radius: calc(2 * var(--borderWidth));
z-index: -1;
animation: animatedgradient 3s ease alternate infinite;
background-size: 300% 300%;
}
#keyframes animatedgradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin-Pan! by Asad</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="gradient-border" id="box">
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
</div>
<div class="gradient-border box-2" id="box">
<span>password:</span>
<div class="numbers">
<input type="number" autofocus class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>

I’m not sure if I understood you question, but here’s my approach:
I’ d use recursive functions to ensure it’s called after the user did something:
function rec(num){
if (num<NumberOfElements){
let el=document.querySelectorAll(".text")[num]//select current element
el.addEventListener("input", function(){//check for input
//do something
//. /do something
num++
rec(num)//recall the recursive function (“loop again”)
}
}}
I didn’t tried the code and you’ll have to customise this for your needs.

Related

How do I keep adding the values of my input fields into another tag

I am trying to get the values from the two input boxes below the "Welcome to Discussion Portal" i.e. input boxes with the ids "textarea_text" and "id2"
and put these values on the left side two made tags i.e. h2 tag and p tag with the ids "addh2_in_col1" and "addp_in_col1"
The values are getting added but,
the problem is that they keep getting updated every time i click the submit button.
I want all the the values keep getting added to there
Here is my code:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<style>
#h1a{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,120,1) 37%, rgba(0,212,255,1) 100%);
color: white;
}
button{
background-color: #0099ff;
height: 48px;
width: 200px;
}
#id1{
height: 45px;
width: 200px;
}
* {
box-sizing: border-box;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
height: 300px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
textarea{
width: 250px;
height: 100px;
}
</style>
<script>
function function2(){
var a = document.getElementById('id2').value;
document.getElementById("addh2_in_col1").innerHTML = a;
var b = document.getElementById('textarea_text').value;
document.getElementById('addp_in_col1').innerHTML = b;
}
</script>
<div class="row">
<h1 id="h1a">Discussion Portal</h1>
<div class="column">
<button>New Question Form</button> <input id="id1" type="text" placeholder="search questions..." ><br>
<div class="div-2">
<h2 id='addh2_in_col1'></h2>
<p id='addp_in_col1'></p>
</div>
</div>
<div class="column">
<h1>Welcome to Discussion Portal</h1>
<p>Enter a subject and question to get started</p><br>
<input id="id2" type="text" placeholder="subject" ><br><br><br>
<textarea id="textarea_text" placeholder="Question"></textarea><br>
<input type="submit" value="Submit" onclick="function2()">
</div>
</div>
</body>
</html>```
You replaced your variable each time you clicked. I made it with array and plus
function function2(){
let a = []
let b = []
a.push(document.getElementById('id2').value);
a.forEach((item) => {
const para = document.createElement("h2");
para.innerHTML += item;
document.getElementById("div-2").appendChild(para);
})
b.push(document.getElementById('textarea_text').value);
b.forEach((item) => {
const para = document.createElement("p");
para.innerHTML += item;
document.getElementById("div-2").appendChild(para);
})
}
#h1a{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,120,1) 37%, rgba(0,212,255,1) 100%);
color: white;
}
button{
background-color: #0099ff;
height: 48px;
width: 200px;
}
#id1{
height: 45px;
width: 200px;
}
* {
box-sizing: border-box;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
height: 300px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
textarea{
width: 250px;
height: 100px;
}
<div class="row">
<h1 id="h1a">Discussion Portal</h1>
<div class="column">
<button>New Question Form</button> <input id="id1" type="text" placeholder="search questions..." ><br>
<div class="div-2" id="div-2">
<h2 id='addh2_in_col1'></h2>
<p id='addp_in_col1'></p>
</div>
</div>
<div class="column">
<h1>Welcome to Discussion Portal</h1>
<p>Enter a subject and question to get started</p><br>
<input id="id2" type="text" placeholder="subject" ><br><br><br>
<textarea id="textarea_text" placeholder="Question"></textarea><br>
<input type="submit" value="Submit" onclick="function2()">
</div>
</div>

How would i align my image above everything else on the page?

I'm trying to get this image, which will end up being a logo, to appear above the table. Everything i have tried has just moved the image beside the other content rather than above it.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline:none;
text-align: center;
}
header label {
display:block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align:center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<body>
<main>
<header>
<img src="../Documents/RMS Logo - Oval.png" width="300" height="175" align="centre">
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
<div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
<script type="text/javascript">
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
</script>
</body>
</html>
I have tried aligning it to "top" and i cant find anything that makes it appear above, what would be the best and most simple way for me to move this image above?
Your HTML structure is wrong. The image shouldn't be inside the <head> tags. The head tag should be used for loading scripts for example. The <header> should not be repeated. I suggest to start by learning the basics of HTML structure here https://www.w3schools.com/html/html_intro.asp
That said, I've moved the image outside the head. I've placed the image inside the <header>. If you want to center the image, make the header 100% width, then apply display: block; to your image and margin: auto;.
See example below.
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
header {
width: 100%;
}
header img {
display: block;
margin: auto;
}
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline: none;
text-align: center;
}
header label {
display: block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align: center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
<!DOCTYPE html>
<html>
<head>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<main>
<header>
<img src="../Documents/square.jpg" width="300" height="175" align="top">
</header>
<div>
<div>
<strong>Enter NHS Price Below</strong>
<input id="myInput" />
</div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
</body>
</html>
You can place it within your header tag but before the label
<header>
<img src="../Documents/square.jpg" width="300" height="175" align="top" >
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
you can also place it before the main tag which might be a bad practice though you might need to create a menu/nav-bar containing the image link
<nav>
<img src="../Documents/square.jpg" width="300" height="175" align="top" >
</nav>
I removed the image and create a class called image-top and added backgroud image their . Is this the thing are u asking about?
<!DOCTYPE html>
<html>
<head>
<!-- <img class="image-t" src="../Documents/square.jpg" width="300" height="175" align="top" > -->
</head>
<style>
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
.image-top{
height: 50vh;
background-image: url('https://www.hackingwithswift.com/uploads/matrix.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline:none;
text-align: center;
}
header label {
display:block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align:center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<body>
<div class="image-top">
<p>img</p>
</div>
<main>
<header>
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
<div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
<script type="text/javascript">
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
</script>
</body>
</html>
To move something above something use position: relative or position: absolute and add z-index higher, than element after it.
E.g.:
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
left: 10px;
top: 10px;
z-index: 1;
}
</style>
</head>
<body>
<img src="https://via.placeholder.com/150">
<p>Text after image Text after image Text after image Text after image Text after image Text after image Text after image</p>
</body>
</html>
If that not your question, sorry, I did not correctly understand :)

Prevent input field from any changes except with arrow buttons

I want to prevent completely users to modify the values of the number input form in any way that is not using the arrows in the form. Basically I have this:
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" onKeyDown="return false" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Note that in the input, I added onKeyDown="return false", an answer in other post like this one.
However, this is not going to prevent the user from doing a paste of any value he wants, nor moving a value with the mouse into the field. Is there any way to prevent it?
You can easily block any events you want with event handlers like this - it takes a list of events and adds an event handler for each to block it. You can add as many or few events as you need - see a list of Events here:
"keypress paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
Working Example - Accessible Version: Allows tab and arrow keys
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
"keypress paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Blocking ALL Key Presses
Note that it is not recommended to prevent all keyDown/keyUp events, for accesibility reasons - it makes your form impossible to use without mouse/touch screen - not only are you unable to change the values, you get stuck inside that input forever and can't even tab out of it! \
Therefore I use keypress instead of keydown above, as keypress allows for control keys to work but if you really need to, you can use keydown instead.
Working Example Blocking ALL Key Presses (inaccessible for visually impaired users)
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
"keydown paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Note, you no longer need the onkeydown or other event handlers on the input itself in either of these examples
By using event listeners, if the user focuses on the input then blur:
jQuery:
$("input").on("focus", function() {
$(this).blur();
});
Vanilla:
const input = document.querySelector("input#len");
input.addEventListener("focus", function() {
input.blur();
});

Javascript file partially running

So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

How do I give elements with the same class name to perform the same function in javascript?

I have multiple elements with the same class name and want them to perform the same javascript function but output their unique "inner.Text" specific
to the element i clicked. Right Now i know i need an [index] and a loop
but I just don't know how to implement that at the moment since im a novice in javascript.
spent 3 hours trying to figure it out
const myButton = document.querySelectorAll('.clipboard-icon');
const myInp = document.querySelectorAll('.snippetcode');
myButton.forEach(ree =>
ree.addEventListener('click', copyElementText));
function copyElementText(id) {
var text = myInp.innerText;
var elem = document.createElement("textarea");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
console.log('clicked');
}
console.log(myButton);
console.log(myInp);
/*everything works fine if the script was changed to affect only ONE class name but I cant figure out how to make them work for more than one
*/
.snippet1 {
border: solid rgb(55, 63, 184) 3px;
}
.snippet_holder {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
padding: 0 3.5rem;
margin: 0 0 1rem 0;
position: relative;
}
.buttons {
width: 170px;
height: 40px;
border: 0;
padding: 0;
font-size: 1rem;
color: #fff;
border-radius: 10px;
}
.snippet_holder:hover .clipboard-icon {
display: block;
position: absolute;
top: 15px;
right: 65px;
background: rgb(51, 153, 136);
margin: 0;
width: 30px;
padding: 0;
height: 30px;
}
.clipboard-icon {
display: none;
}
.clipboard-icon img {
width: inherit;
height: inherit;
position: relative;
}
.clipboard-icon pre {
display: none;
}
.snippetcode1 {
display: none;
}
.button1 {
-webkit-animation: rainbow 6.5s ease infinite;
animation: rainbow 6.5s ease infinite;
background-image: linear-gradient(124deg, #ff470f, #ff3860, #b86bff, #3273dc);
background-size: 800% 800%;
}
#keyframes rainbow {
0% {
background-position: 1% 80%;
}
50% {
background-position: 99% 20%;
}
100% {
background-position: 1% 80%;
}
0% {
background-position: 1% 80%;
}
50% {
background-position: 99% 20%;
}
100% {
background-position: 1% 80%;
}
}
main {
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<html>
<body>
<main>
<div class="snippet_holder snippet_holder1">
<div class="clipboard-icon">
<pre>
<code class= "snippetcode">
1st class text copieddddd
</code>
</pre>
<img src="https://www.shareicon.net/data/128x128/2016/04/27/756265_clipboard_512x512.png">
</div>
<button type="button" class="buttons button1">button</button>
</div>
<div class="snippet_holder snippet_holder1">
<div class="clipboard-icon">
<pre>
<code class= "snippetcode">
22222nddd class text copieddddd
</code>
</pre>
<img src="https://www.shareicon.net/data/128x128/2016/04/27/756265_clipboard_512x512.png">
</div>
<button type="button" class="buttons button1">button</button>
</div>
<div class="snippet_holder snippet_holder1">
<div class="clipboard-icon">
<pre>
<code class= "snippetcode">
3rd class text copieddddd
</code>
</pre>
<img src="https://www.shareicon.net/data/128x128/2016/04/27/756265_clipboard_512x512.png">
</div>
<button type="button" class="buttons button1">button</button>
</div>
<div class="snippet_holder snippet_holder1">
<div class="clipboard-icon">
<pre>
<code class= "snippetcode">
4thhhhhhhhclass text copieddddd
</code>
</pre>
<img src="https://www.shareicon.net/data/128x128/2016/04/27/756265_clipboard_512x512.png">
</div>
<button type="button" class="buttons button1">button</button>
</div>
</main>
</body>
</html>
You've to query the .snippetcode related to the button pressed, so, it makes no sense to query the nodeList myInp, you can access to the right element using the currentTarget provided in the event object...
function copyElementText(event) {
var text = event.currentTarget.querySelector('.snippetcode').innerText;
var elem = document.createElement("textarea");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
console.log('clicked');
}

Categories