How do I change this code so that when I select an input it adds the text from array based on input id. I have tried to do it myself, but in for loop "i" is always equal to 2, but I want it to be 0, 1 based on which input I select. Please help, I have spent multiple hours with no success.
let basetext = [];
let text1 = document.getElementById("text")
text1.innerHTML = basetext
const thank = [`hi`,
`bye`]
for (i=0; i<thank.length; i++) {
document.getElementById("thank"+i).addEventListener("click", function () {
basetext[i] = thank[i]
text1.innerHTML = basetext.join('')
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div>
<input type="radio" name="thank" id="thank0" />
<label for="thank0">first</label>
<input type="radio" name="thank" id="thank1" />
<label for="thank1">second</label>
</div>
<button>Next</button>
</div>
</div>
</body>
<script src="index.js"></script>
</html>
Add a data attribute to each input.
Add a class to a containing element, and then use event delegation to catch events from the child input elements when they're fired. In the handler check to see if the child element that fired the event is a radio input, and then use the data attribute to grab the element from the thank array, and update the textarea content with it.
// Cache the elements
const text = document.querySelector('#text');
const group = document.querySelector('.inputGroup');
// Add one listener to the input group element
group.addEventListener('change', handleChange);
const thank = [`hi`, `bye`];
// Check that clicked input is a radio button,
// grab the id from its dataset, and then use
// that id to add the element from the array to
// the content of the text area
function handleChange(e) {
if (e.target.matches('[type="radio"]')) {
const { id } = e.target.dataset;
text.defaultValue = thank[id];
}
}
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div class="inputGroup">
<label for="0">first
<input
type="radio"
name="thank"
data-id="0"
id="thank0"
/>
</label>
<label for="thank1">second
<input
type="radio"
name="thank"
data-id="1"
id="thank1"
/>
</label>
</div>
<button>Next</button>
</div>
</div>
Related
I am making a note-taking app and I want 2 text areas to when you type in one the other changes to
what you are doing in one. I want so when I change the title of the page it will change in other places on the page. I'll provide my current code what my page looks like (I want the change to be with my Unititled and an area next to the dropdown arrow) and what I want it to do, I've tried change and input events and I can't seem to figure it out.[My Current Site][1]
What I Want - https://share.vidyard.com/watch/Wj6uTmEiB9LR8iiZy7sVf9
[1]: https://i.stack.imgur.com/3vzEB.png
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Study App</title>
<link rel="stylesheet" href="study.css" />
<link href="https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/5.15.1/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-
8"></script>
</head>
<body>
<script src="study.js"></script>
<div class="dropdown">
<nav><label for="touch"><span>Settings</span></label>
<input type="checkbox" id="touch" />
<ul class="slide">
<li><a>
<div class="dark"><button onclick="myFunction()">
<input class="toggle" type="checkbox" /></button></div>
</a></li>
<li></li>
</ul>
</nav>
</div>
</div>
<div class="arrowdown">
<input type="checkbox" id="myCheckbox" onchange="rotateElem()" checked><i class="fas fa-angle-
right dropdown"></i></button>
<div class="pages">
Add Page
</div>
</div>
</div>
<script type="text/javascript">
var checkBox = document.getElementById("myCheckbox");
function rotateElem() {
if (checkBox.checked == false) {
document.querySelector('.fas.fa-angle-right.dropdown').style.transform = 'rotate(90deg)';
} else {
document.querySelector('.fas.fa-angle-right.dropdown').style.transform = 'rotate(0deg)';
}
}
</script>
<div class="tabs"></div>
<div class="sidebar">
<div class="sidebar-top">
<h1><span class="study">Study</span><span class="app">App</span></h1>
</div>
<div class="title">
<textarea id="shortInput" spellcheck="true" placeholder="Untitled" cols="30" rows="1">
</textarea>
</div>
<div class="textbox">
<textarea id="longInput" spellcheck="true" placeholder="Start typing..." cols="30" rows="10"></textarea>
</div>
<script type="text/javascript">
$('.pages').hide();
$(document).ready(function() {
$('input').click(function() {
$('.pages').slideToggle();
});
});
</script>
<script src="study.js"></script>
</body>
</html>
One possible approach would be to store the synchronised value in a variable, and add event listeners to each element for any changes. Then update the value of each element with the new value when the change occurs.
// Store the synchronised content
let value = ''
// Add change listeners to each element
const elements = document.querySelectorAll('.synced')
for (let i = 0; i < elements.length; i++) {
// Different browsers will work better with different events
// but there's no problem with listening for multiple
elements[i].addEventListener('change', handleChange)
elements[i].addEventListener('input', handleChange)
elements[i].addEventListener('keyup', handleChange)
}
// When a change occurs, set the value of all the synchronised elements
function handleChange(e) {
value = e.target.value
for (let i = 0; i < elements.length; i++) {
elements[i].value = value
}
}
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
jQuery version:
// Store the synchronised content
let value = ''
// Get all the of the relevant elements
const elements = $('.synced')
// Different browsers will work better with different events
// but there's no problem with listening for multiple
elements.on('change input keyup', function() {
value = $(this).val()
elements.val(value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
I have a Currency Converter , consisting of two fields and a button. In the first field I type the amount I want to be converted, in the second field I get the result of the conversion.
The question is:
When I type text in the first field, how can I clean up the text from the second field with the conversion result? Using a Javascript / Jquery function?
Thanks in advance.
This is my code:
function convertiLireInEuro() {
var importoInserito = $('#txtLireEuro').val();
importoInserito = importoInserito.replace(/,/g, '.');
var lire = parseFloat(importoInserito)
var euro = lire * 1000 / 1936.27
euro = euro.toFixed(2);
euro = Math.round(euro);
$('#txtConversione').val(euro); }
HTML:
<input type="text" id="txtLireEuro" name="txtLireEuro" style="text-align:right" onkeypress="return onlyNumbers(event);" /> 000 ₤
<input value="Converti in Euro" type="button" id="btnLireEuro" name="btnLireEuro" style="margin-left: 20px" onclick="convertiLireInEuro();highlightAndCopyText();"/>
<input type="text" id="txtConversione" name="txtConversione" style="text-align:right;margin-left:20px" readonly /> €
<span class="Label" style="margin-left:12px">(importo già arrotondato all’intero e incollabile nel campo desiderato)</span>
Here is what you need, I post a coding snippet. I have 2 fields, typing-field and field-to-reset. If you first fill in the field-to-reset with some text and then start typing in typing-field the field-to-reset will reset.
let typing = document.getElementById("typing-field");
let reset = document.getElementById("field-to-reset");
typing.addEventListener("keydown", () => {
reset.value = "";
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>Typing field:</div>
<input id="typing-field" type="text">
<div>Field to reset:</div>
<input id="field-to-reset" type="text">
</body>
</html>
HTML Code
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
JQuery Code
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#input_box").keydown(function(){
$("#result_box").val("");
})
});
</script>
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
When "Input_box" is getting focus on click the result_box will clear
it's value.
You already have an onkeypress event listener named onlyNumbers. You can simply put $('#txtConversione').val = ""; in that function.
I'm trying to make a simple webshop cart and i'm currently stuck with a problem.
I want to increase or decrease the value of the input whenever i click on the plus or minus button.
To show the plus and minus button, please click "add to cart".
How do i increase or decrease the value of the input whenever i click on the plus or minus button?
Thank You in Advance.
const foodList = document.getElementById('foodList');
const foodListOrder = document.getElementById('foodOrderList');
const inputAmount = document.getElementById('input');
const plusBtn = document.getElementById('plusBtn');
const minusBtn = document.getElementById('minusBtn');
foodList.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
let parentButton = event.target.parentNode;
let button = parentButton.firstElementChild;
let addListOrder = document.createElement('li');
parentButton.removeChild(button);
addListOrder.innerHTML = `${parentButton.textContent} <input type="text" id="input" value="1"> <button id="plusBtn">+</button> <button id="minusBtn">-</button>`
foodListOrder.appendChild(addListOrder);
}
})
ul li {
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<p>Food List</p>
<ul id="foodList">
<li>Chicken <button>Add to cart</button></li>
<li>Meat <button>Add to cart</button></li>
<li>Hot-Dog <button>Add to cart</button></li>
<li>Fries <button>Add to cart</button></li>
<li>Hamburger <button>Add to cart</button></li>
<li>Ice-Cream <button>Add to cart</button></li>
<li>Spaghetti <button>Add to cart</button></li>
</ul>
</div>
<hr>
<div>
<p>My Shopping Cart</p>
<ul id="foodOrderList">
</ul>
</div>
<script src="javascript.js"></script>
</body>
</html>
Well what can you do is instead of giving static and same id for each plus and minus button you can give them dynamic IDs in the basis of your item.
Something like
addListOrder.innerHTML = `${parentButton.textContent} <input type="text" id=${input + parentButton.textContent}value="1"> <button id=${add + parentButton.textContent}>+</button> <button id=${remove + parentButton.textContent}>-</button>`
In this way you will have unique id for every fields and you can add event listener or onClick function to the button or listen to the event fired from which input field using event listener.
Update the value with that ID recieved through event.
I really struggling with this.
I need to basically make it so whatever is written in a newly created textbox is stored in local storage.
// TODO: Q1(c)(iii)
// Make an event listener to save text when it changes:
// ...get the textarea element's current value
// ...make a text item using the value
// ...store the item in local storage using the given key
// Connect the event listener to the textarea element
var item, data, key;
var textareaElement = document.createElement("TEXTAREA");
textareaElement.addEventListener("change", function(event) {
var myText = document.getElementById("textareaElement").value;
localStorage.setItem("text", myText);
item = makeItem ("text", myText);
});
-- HTML --
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Erehwon Diary ds22368</title>
<meta name="author" content="Stephen Rice" />
<!-- Set viewport to ensure this page scales correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="tma03.css" />
<!-- Set demo data -->
<script src="tma03-demo.js"></script>
<!-- Start TMA03 application -->
<script src="tma03.js"></script>
</head>
<body>
<h1>My Erehwon Diary ds22368</h1>
<main>
<section id="text" class="button">
<button type="button">Add entry</button>
</section>
<section id="image" class="button">
<button type="button">Add photo</button>
<input type="file" accept="image/*" />
</section>
</main>
</body>
</html>
The questions for each line are the comments above, and below them is what I've tried so far.
var item, data, key;
var textareaElement = document.createElement("TEXTAREA");
document.body.appendChild(textareaElement); //Add the element to the document
textareaElement.addEventListener("change", function(event) {
var mytext = textareaElement.value; //You already have the element as a variable
localStorage.setItem("text", myText);
item = makeItem("text", myText);
});
function makeItem() { //Don't forget to define makeItem
//code
}
Create an input like this in your HTML
<textarea id=‘textarea’ onchange=‘save()’ />
In JS:
const textarea = document.querySelector(‘#textarea’)
function save() {
localStorage.setItem("text", textarea.value);
}
I am a freshman at a university. I have been given an assignement where I need to use addEventListener. The problem is that I haven't used it before.
What this assignment is, is that I have a json file With a list of student names. My first exercise was to show a list of all the students. I did that. But then comes the hard part, where I can't find a possible solution, when I need to show only students that are in a certain program. There are radio buttons for each of the programs and when clicked a list of the members of the program need to show up. Also there is a radio button that says "all", which need to Select all the students.
Here is my javascript file:
.then((response) => {
return response.json();
})
.then(function appendData(data) {
var unordered = document.querySelector(".studenter");
for (var i = 0; i < data.length; i++) {
var li = document.createElement("li");
li.innerHTML = 'Name: ' + data[i].fornavn + ' ' + data[i].etternavn;
unordered.appendChild(li);
}
});
Here is the HTML file:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Studenter i IIKG1002 og IDG1011</title>
<script defer src="js/studenterIKlasse.js"></script>
<link rel="stylesheet" href="css/studenterIKlasse.css" />
</head>
<body>
<h1>Studenter i IIKG1002 og IDG1011</h1>
<p>Velg klasse</p>
<div class="klasseVelger">
<div>
<input type="radio" name="programvelger" id="BIGEOMAT" />
<label for="BIGEOMAT">Bachelor in Engineering, Geomatics</label>
</div>
<div>
<input type="radio" name="programvelger" id="BWU" />
<label for="BWU">Bachelor in Web Development</label>
</div>
<div>
<input type="radio" name="programvelger" id="ÅRWEB" />
<label for="ÅRWEB">Web Design - One-year programme</label>
</div>
<div>
<input type="radio" name="programvelger" id="BIXD" />
<label for="BIXD">Interaction Design - Bachelor's Programme</label>
</div>
<div>
<input type="radio" name="programvelger" id="all" />
<label for="all">Show all</label>
</div>
</div>
<p>
<ul class="studenter"></ul>
</p>
</body>
</html>
And here is an example of what the student Object look like (json):
{
"fornavn": "Marcus Gimse",
"etternavn": "Blikstad",
"studieprogram": "Bachelor in Engineering, Geomatics",
"forkortelse": "BIGEOMAT"
},