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

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>

Related

sending commands/values between pages

im working on a website with 2 pages 1 is the receiver and 2 is the remote basicly you can enter a text on page 2 and once you hit submit page1 starts playing a text to speatch message with the text inut from page2
index.html (aka : page1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
control.html (aka : page2)
<body>
<center>
<form>
<h1 style="color:green">Javatpoint</h1>
<h3> Confirm password Validation Example </h3>
<!-- Enter Password -->
<td> Enter Password </td>
<input type = "password" name = "pswd1"> <br><br>
<button type = "submit" onclick="matchPassword()">Submit</button>
<script>
var pw1 = document.getElementById("pswd1");
function matchPassword() {
<script src="script.js"><script> var x1
}
</script>
script.js of page1
const message = 'Hello world' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = "hallo jeremy";
window.speechSynthesis.speak(msg);
i cant find a way to send the text inside page2 to page 1
There are many ways that you could achieve this, but I'll show you just one. You can easily pass data between pages using query parameters, which are essentially pieces of data appended to the end of a URL.
In order to utilize these, you would need to redirect to your index.html page whenever the user presses the button in the control.html page. Fortunately, this can be done by adding an event listener to your Submit button.
Here is the code below:
control.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" />
</head>
<body>
<form>
<p>Enter stuff here:</p>
<input type="text" id="text-input" name="text" />
<input type="submit" id="submit-button"></input>
</form>
<!-- continue document... -->
<script src="src/control.js"></script>
</body>
</html>
src/script.js
const queryString = window.location.search;
const queryParams = new URLSearchParams(queryString);
const message = queryParams.get("text");
console.log(message);
// continue file...
src/control.js
const button = document.getElementById("submit-button");
button.addEventListener("click", handleText);
function handleText(event) {
event.preventDefault();
const text = document.getElementById("text-input").value;
const currentURL = window.location.pathname;
const currentDir = currentURL.substring(0, currentURL.lastIndexOf("/"));
window.location.replace(currentDir + "/index.html?text=" + text);
}
Hope this helps!

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.

Im new with call api , can someone help me with this . Call Api link shortener with javascript

So I have a mission is call api to this website : https://shrtco.de/ and using link shortener like them. But I don't know how to call it . Can someone explain how to call this or maybe help me , thank you guys so much
This is 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">
<title>Document</title>
</head>
<body>
<div>
<p>Enter a link</p>
<input type="text">
<button>Enter</button> <br>
<p>Short domain</p>
<input type="radio" id="domain1" name="fav_language" value="domain1">
<label for="html">shrtco.de</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">9qr.de</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">shiny.link</label>
<p>Link generated</p>
ZZZZZ
</div>
<script src="getAPI.js"></script>
</body>
</html>
Following the example from the interface documentation, I have programmed a minimal illustrative example here.
<!DOCTYPE html>
<html>
<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>shortcode example</title>
</head>
<body>
<input type="text" name="url" id="url" value="" required>
<button id="submit" type="submit">shorten</button>
<p id="result"></p>
<script>
const button = document.querySelector('button');
const input = document.querySelector('input');
const result = document.getElementById('result');
const shorten = (event) => {
let value = input.value.trim();
while (result.firstChild) {
result.removeChild(result.firstChild);
}
if (!value.length) {
throw new Error('well! you have to type in something!');
}
let promise = fetch('https://api.shrtco.de/v2/shorten?url=' + value);
promise.then(response => {
if (response.status !== 201) {
console.log('Looks like there was a problem: ' + response.status);
return;
}
response.json().then(data => {
let link = document.createTextNode(data.result.full_short_link);
result.appendChild(link);
}).catch(error => {
console.log(error.message);
})
});
}
button.addEventListener('click', shorten, false);
</script>
</body>
</html>
What is happening in this example?
First there are three elements - an input element for typing in the url to shorten, a button element for submitting the data and a paragraph for displaying the results of the api call.
The submit button gets an javascript event listener, that handles click events. Everytime you click on that button, the input element will be checked, if something was typed in. If the value of the input element has a length, it will be send to the shortening service. For that reason we produce a promise with the javascript fetch api.
The call with the fetch api returns a javascript promise, which we check for the response status code. The api returns a 201 "Created" status code, that says everything is alright. The api needs a little time for the response, but then we can decode the json response and print out the shortened link in the result paragraph.
What you should do
Try to understand the given example. Please read the interface documentation to get informations about what could be returned in a success case and whats happening when the request fails? The javascript fetch api is elemental for that.
Try to transfer the given example to your application. If you encounter problems, explain these problems in detail and ask for a solution.

What could be wrong with my keypress event?

I'm trying to make a weather app, and use the API from openweathermap, I copied the baseurl from the web like this but it's not currently working...
const api = {
key:"03173bc8739f7fca249ae8d681b68955"
baseurl:"https://home.openweathermap.org/api_keys"
}
const searchbox=document.querySelector('.search-box');
searchbox.addEventListener('keypress', setQuery)
function setQuery(evt){
if (evt.keyCode==13)
//getResults(searchbox.value)
console.log(searchbox.value)
}
So when I type in the search box, the console doesn't show anything...
This is my html file:
<!DOCTYPE html>
<html>
<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> </title>
<link rel="stylesheet" href="weather.css">
</head>
<body>
<div class="app-wrap">
<header>
<input type="text" autocomplete="off" class="search-box" placeholder="Search for a city...">
</header>
<main>
<section class="location">
<div class="city">HCM City, Viet Nam</div>
<div class="date">Friday 25 June 2021</div>
</section>
<div class="current">
<div class="tempt">15<span>°C</span></div>
<div class="weather">Sunny</div>
<div class="high-low">13°C / 16°C</div>
</div>
</main>
</div>
<script src="weather.js"></script>
</body>
</html>
Is there something wrong with the baseurl or something, can anybody tell me?
wrap the selector with " ";
const searchbox = document.querySelector(".search-box");
also correct your api obj:
const api = {
key: "03173bc8739f7fca249ae8d681b68955",
baseurl: "https://home.openweathermap.org/api_keys"
}
You missed to add single quote in querySelector.
const searchbox=document.querySelector('.search-box'); // Corrected
also you need to update the API object
const api = {
key:"03173bc8739f7fca249ae8d681b68955",
baseurl:"https://home.openweathermap.org/api_keys"
}

how do i connect event listener to textarea element?

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

Categories

Resources