how do i connect event listener to textarea element? - javascript

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);
}

Related

How can I directly display a value from an excel cell without ActiveX? [duplicate]

I'm trying to create a trigger button that, when pressed, will display a value from an excel cell in alert box or on the page.
below is all I could get, but it doesn't display anything on the page.
update: I managed to do this using ActiveX, but I don't want to use this library for some reasons. Do you have any idea how I could do it?
update code:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Excel to HTML</title>
</head>
<body>
<p>Press to show</p>
<input type="button" onclick="ReadData(4, 2) ; msgprint()" value="Show" />
<div id="div1">
<script>
function ReadData(cell, row) {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("mypah/myworkbook.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var data = excel_sheet.Cells(cell, row).Value;
document.getElementById("div1").innerText = data;
}
</script>
</div>
<script>
function msgprint() {
alert(document.getElementById("div1").innerText);
}
</script>
</body>
</html>

todos list with a saved array and then retrieve it stuck?

i started an app todoslist , after creating first code simply of adding new todos in DOM
now my task is this :
addtodo :
// grab todo value
// pu tit in the array
// tell the draw method to redraw the todos
drawtodo :
grab the array
for each text add a todo entry in the documen
the array
my html code
<!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">
<link rel="stylesheet" type="text/css" href="style.css">
<title>TodoList</title>
</head>
<body>
<div class="todolist_box">
<h3> To Do List </h3>
<div class="input">
<input type="text" id ="inp" placeholder="Add new Task">
<button onclick="newTodo()" ><i> enter </i></button>
<button onclick="newTodo()" ><i> save </i></button>
<button onclick="drawtodo()" ><i> load </i></button>
</div>
<ul id="myUL">
</ul>
</div>
<script src="script.js" type="application/javascript"></script>
</body>
</html>
and this is my javascript code
function newElement() {
// this code doesn't work, but it gives you an idea
const li = document.createElement("li")
const newEntry = document.getElementById("inp").value
const u = document.createTextNode(newEntry)
li.appendChild(u)
document.getElementById("myUL").appendChild(li)
document.getElementById("inp").value = "Nothing"
// something like thi
let todos = []
function newTodo() {
let inpvalue = document.getElementById('inp').value
todos.push(inpvalue)
// trigger draw event
}
function drawtodo() {
for (var i = todos.length - 1; i >= 0; i--) {
let li = document.createElement('li')
let newlist = li.appendChild(document.createTextNode(todos[i]))
inpvalue.appendChild(newlist)
}
}
document.onload = function() {
// this will excute when the document loads
}
}
Try using Javascript event listener instead of onclick attribute in html.
HTML:
<button id="load" ><i> load </i></button> // Removed onclick attribute
JS:
document.getElementById("load").addEventListener("click", drawtodo, false);
same with enter and save buttons, when click triggers the newTodo function.

How can I get search functionality to work when typing in search queries in the input box?

I am making a news style app that uses the newsapi. I want to ask how do I get search functionality to work, how do I get the HTML input box to display the results of what you type in. I have tried a few times to get it to work but can't. Any suggestions appreciated.
HTML
<!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">
<link rel="stylesheet" href="css/style.css">
<title>News App</title>
</head>
<body>
<header>
<h1 class="heading">News</h1>
<form class="searchform" autocomplete="off">
<input class="searchBox" name="search" type="text" >
<button type="submit">Submit</button>
</form>
<li class="newsList"></li>
<script src="js/main.js"></script>
</header>
</body>
JavaScript
const newsList = document.querySelector(".newsList")
const newsImage = document.querySelector(".newsList")
const form = document.querySelector("form.search")
newsImage.innerHTML = ''
newsList.innerHTML= ''
const url = 'https://newsapi.org/v2/everything?' +
'q=${search}&' +
'from=2021-06-02&' +
'sortBy=popularity&' +
'apiKey=****************';
let req = new Request(url);
fetch(req)
.then(function(response) {
return response.json()
}).then((data)=>{
console.log(data)
data.articles.map(article => {
let li = document.createElement('li')
let a = document.createElement('a')
let image = document.createElement('span')
image.innerHTML = `<img src="${article.urlToImage}" >`
a.setAttribute('href', article.url)
a.setAttribute('target','_blank' )
a.textContent = `${article.title}`
li.appendChild(a)
newsList.appendChild(li)
newsImage.appendChild(image)
});
})
function handleSubmit(e){
e.preventDefault()
console.log(e.target)
}
form.addEventListener('submit', handleSubmit)
Okay so I don't have an API key to the news API that you are using but I instead used a free Rick & Morty API to answer your question.
I had to make some alterations to your code in order to get it to work with my API but I added a bunch of comments in the code snippet to hopefully make it make a bit of sense why I made the changes and also how you can change it back to work with your news API. Good luck!
const characters = document.querySelector(".characters");
const searchInput = document.querySelector("#search");
characters.innerHTML = "";
// We also changed this here to include the actual act of fetching the data - you would instead do your news fetch here.
function handleClick(e) {
let url = "https://rickandmortyapi.com/api/character/";
// This here maps a HTMLCollection into a JavaScript array and then removes previous children if they exist,
// this is to clear the list items prior to a new search.
if (characters.children.length > 0)
Array.from(characters.children).forEach((child) => child.remove());
// If we provide a search input include it in the URL - note the only search we can do here is for pages so the input is now a number.
// This is where you would instead change your news URL and append the "searchInput.value" into the "search section" like so:
//
// const url =
// "https://newsapi.org/v2/everything?" +
// `q=${searchInput.value}&` +
// "from=2021-06-02&" +
// "sortBy=popularity&" +
// "apiKey=****************";
//
// Note that in order to use a variable you need backticks as your quote delimeter. See like `${variable}` instead of '' or "".
if (searchInput.value)
url =
"https://rickandmortyapi.com/api/character/" +
`?page=${searchInput.value}`;
let req = new Request(url);
fetch(req)
.then(function (response) {
return response.json();
})
.then((data) => {
console.log(data);
// I removed your image mapping here because I had no image from this free Rick and Morty API but I hope you get the idea.
data.results.map((character) => {
let li = document.createElement("li");
let a = document.createElement("a");
a.setAttribute(
"href",
"https://rickandmortyapi.com/api/character" + `/${character.id}`
);
a.setAttribute("target", "_blank");
a.textContent = `${character.name}`;
li.appendChild(a);
characters.appendChild(li);
});
});
}
<!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" />
<!-- I removed this because I had no css file -->
<!-- <link rel="stylesheet" href="css/style.css" /> -->
<title>Test App</title>
</head>
<body>
<header>
<h1 class="heading">Test</h1>
<form class="searchform" autocomplete="off">
<!-- <input id="search" class="searchBox" name="search" type="text" /> -->
<!-- Because my search in the free API could only handle numbers I changed the type here -->
<!-- You will want to change that back to the above commented out text field -->
<input id="search" class="searchBox" name="search" type="number" />
<!-- Instead of using prevent default I changed the action here to be the onclick of the button -->
<!-- That fires off our "handleClick()" method that lives in our main.js file -->
<button type="button" onclick="handleClick()">Submit</button>
</form>
<div class="characters"></div>
<script src="main.js"></script>
</header>
</body>
</html>

input field won't clear up

I can't clear up my input field even tho i followed a tutorial step by step , i'm making this to do list and I want the input field to be clear anytime i submit a new to do . so what is wrong with my code ?
ps : i tried to clear the cache and nothing
let addButton=document.getElementById('addButton');
let toDoContainer = document.getElementById('ToDoContainer');
let inputField = document.getElementById('text');
//event listeners
addButton.addEventListener('click',addTodo);
//functions
function addTodo(event,title){
event.preventDefault();
//create the to do
let toDoDiv = document.createElement('div');
toDoDiv.classList.add('todo');
const newToDo =document.createElement('p');
newToDo.innerHTML=inputField.value;
newToDo.classList.add('todo-item');
toDoDiv.appendChild(newToDo);
toDoContainer.appendChild(toDoDiv);
//check mark button
const completedButton = document.createElement('button');
completedButton.innerHTML="success";
completedButton.classList.add("complete-btn");
toDoDiv.appendChild(completedButton);
//check delete button
const trashButton = document.createElement('button');
trashButton.innerHTML="delete";
trashButton.classList.add("complete-btn");
toDoDiv.appendChild(trashButton);
//append todo
toDoContainer.appendChild(tododiv);
inputField.value= "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>to do list </title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<header>
<h1>This is your to do list </h1>
<div class="input">
<input type="text" placeholder="what to do ...?" id="text">
<input type="button" value="add" id="addButton">
</div>
</header>
<div id="ToDoContainer">
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
here is a screenshot
sonEtLumiere is right, you have a typo. It should be:
toDoContainer.appendChild(toDoDiv);
Your variable is called toDoDiv, you have an error in this line (penultimate line):
toDoContainer.appendChild(tododiv);
This will work:
toDoContainer.appendChild(toDoDiv);

Where can I add a second on click function that targets the var "giphyImage"?

I have tried: inside the for loop, inside the .done function but outside the for loop, and before and after the button function end. I'm wanting to be able to run a function on the click of the giphyImage.
Below is the code I am trying to insert somewhere to get the second click and test it in the console but nothing displays in the console at all.
$('giphyImage').on('click', function() {
console.log('testclickedimage')
});
Here is my HTML:
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<!--Megatags-->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Title on browser tab-->
<title>Bradley's Giphy API App</title>
<!--Reset tag-->
<link rel="stylesheet" href="assets/css/reset.css">
<!--Bootstrap tag-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!--Css tag (after bootstrap)-->
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="buttons">
<button data-giphy="cat">Cats</button>
<button data-giphy="dog">Dogs</button>
<button data-giphy="bird">Birds</button>
<button data-giphy="horse">Horses</button>
<button data-giphy="parrots">Parrots</button>
<button data-giphy="jason schwartzman">Jason Schwartzman</button>
<button data-giphy="zooey deschanel">Zooey Deschanel</button>
<button data-giphy="michael cera">Michael Cera</button>
<button data-giphy="zach braff">Zach Braff</button>
<button data-giphy="natalie portman">Natalie Portman</button>
<button data-giphy="pizza">Pizza</button>
<button data-giphy="hamburger">Hamburger</button>
<button data-giphy="beer">Beer</button>
<button data-giphy="shrimp">Shimp</button>
<button data-giphy="lobster">Lobster</button>
</div>
<div class="addButtons"></div>
<div class="gifsAppearHere"></div>
</div>
<!--Jquery tag-->
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<!--Javascript tag-->
<script src="assets/javascript/game.js"></script>
</body>
</html>
Here is my javascript code:
$('button').on('click', function() {
var giphy = $(this).data('giphy');
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + giphy
+ "&api_key=dc6zaTOxFJmzC&limit=10";
//testing variable
console.log (queryURL);
$.ajax({
url: queryURL,
method: 'GET'
}).done(function(response) { //done function
//console logs results remove when done testing
console.log(response)
//pulls response from data key
var results = response.data
//loops though images randomly
for (var i = 0; i < results.length; i++) {
//creates Div
var giphyDiv = $('<div class="giphyDiv">');
//pulls ratings
var p = $('<p>').text('Ratings: ' + results[i].rating);
//creats images
var giphyImage = $('<img>');
//pulls images from API
giphyImage.attr('src', results[i].images.fixed_height.url);
//appends rating and image
giphyDiv.append(p);
giphyDiv.append(giphyImage);
//prepends to class specified in html
$('.gifsAppearHere').prepend(giphyDiv);
} //end of for loop
}); //end of done function
}); //end of button function
::edit:: was able to fix by targeting 'img' instead of 'giphyImage'
$('img').on('click', function() {
console.log('testclickedimage')
});
now console displays 'testclickedimage'
I think your problem is that giphyImage is a string and not a DOM element. That's why you cannot attach an event listener to it.
Try this:
var giphyImage = document.createElement('img');
giphyImage.setAttribute('src', yourImageSource);
giphyImage.addEventListener('click', yourFunctionHere /* without () */);
giphyDiv.appendChild(giphyImage);
Edit
A better way to achieve the same result is to use event delegation.
In short, instead of attaching one event listener to each image element, you can simply attach a single event listener to a parent element, which will fire for all children matching some criteria (for example, a class name). Even better, it does not matter at all if the child already exists or is added at a later time.
Example using pure JavaScript:
var body = document.querySelector('body');
body.addEventListener('click', function(event) {
if (event.target.tagName === 'IMG')
youFunctionHere();
})

Categories

Resources