Textfield Input Value Returning Null - javascript

I'm working on an app that makes fetch calls to a dictionary API based on the user's input. The problem is, I can't seem to get the input value from the search bar. Currently, all that's being logged to the console is an empty string. I currently have my code inside of a DOMContentLoaded event listener. When I take my code out of the DOMContentLoaded function, I am getting a null value returned. This is incredibly straightforward but I can't seem to figure out what is getting muddled here. Here is the code;
window.addEventListener('DOMContentLoaded', () => {
const searchBar = document.getElementById('search-bar');
const userInput = searchBar.value;
const searchButton = document.getElementById('search-button');
const test = () => console.log(userInput);
searchButton.addEventListener('click', test);
});
<!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">
<script src="app.js"></script>
<title>Dictionary</title>
</head>
<body>
<h1>Dictionary</h1>
<input type="text" id="search-bar" placeholder="Find a definition"/>
<button id="search-button">Search</button>
<div id="results-area">
</div>
</body>
</html>
Thanks for the help.

The issue was you're getting always the first value of input which is empty, to get the new value call searchBar.value on the click of button.
window.addEventListener('DOMContentLoaded', () => {
const searchBar = document.getElementById('search-bar');
const searchButton = document.getElementById('search-button');
const getInputValue = () => {
let userInput = searchBar.value;
console.log(userInput);
}
searchButton.addEventListener('click', getInputValue);
});
<!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">
<script src="app.js"></script>
<title>Dictionary</title>
</head>
<body>
<h1>Dictionary</h1>
<input type="text" id="search-bar" placeholder="Find a definition" />
<button id="search-button">Search</button>
<div id="results-area">
</div>
</body>
</html>

Related

Javascript textarea charcoutner isn't working

hello my code isn't working idk why i tried to make textarea char counter that only shows the chachter not maxiumum
here is the java script
let text = document.querySelector('#text');
let number = text.value.length;
let count = document.querySelector('#count');
text.addEventListener("input", updateCount());
function updateCount(){
count.value + number
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
<script src="main.js"></script>
</body>
</html>
In your text.addEventListener("input", updateCount()); assignment you did not assign the function updateCount to the input event of the selected element but instead you executed it once and assigned the non-existent return value of the function call to the event.
And in the function itself you will need to put (=assign) the calculated count somewhere too:
let text = document.querySelector('#text');
let count = document.querySelector('#count');
text.addEventListener("input", updateCount);
function updateCount(ev){
count.textContent=ev.target.value.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
<script src="main.js"></script>
</body>
</html>
ev.target.value.length gets the current length of the <textarea> element and count.textContent= assigns it to the target <span>.
A better way is by subscribing to the keyup event and getting the value from the scope using this keyword
function characterCount() {
document.getElementById('text').onkeyup = function () {
document.getElementById('count').innerHTML = this.value.length;
};
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz" onchange="characterCount()"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
</body>
</html>

I am trying to use an user HTML input to change a javascript object value

I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
const newId = apiData.id;
function eventController(event) {
newId = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>
newId is const, so you cannot assign it with a new value after it has been declared.
But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.
You should just assign apiData.id directly with a new value:
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
// const newId = apiData.id;
function eventController(event) {
apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>

When argument in method is allocated in javascript?

Can you let me know when method(function in a function)'s argument is allocated?
if the arguments in method(in a function)is allocated when they are declared, there's no value of USERNAME.value when it is declared.
but If I put Stored Name as a argument of greeting in function store(which is call back function used for event),null comes out even if I put my user name on in input box.
However, If I put USERNAME.value, it works properly.
This is my js code,
const USERNAME = document.getElementById("username");
const Form = document.querySelector("form");
const HIDDEN = "hidden";
const h2 = document.querySelector("h2");
const KEY = "username";
function greeting(who) {
h2.innerText = `Hello, ${who}`;
h2.classList.remove(HIDDEN);
}
function store(event) {
event.preventDefault();
localStorage.setItem(KEY, USERNAME.value);
Form.classList.add(HIDDEN);
greeting(StoredName);
}
const StoredName = localStorage.getItem(KEY);
if (StoredName == null) {
Form.classList.remove(HIDDEN);
Form.addEventListener("submit", store);
} else {
greeting(StoredName);
}
and this is my html code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="practice.css">
<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>
<h2 class="hidden"></h2>
<form action="" class="hidden">
<input type="text" name="" id="username">
<input type="submit" value="">
</form>
<script src="practice.js"></script>
</body>
</html>

Unable to get response from api and convert it to Json

I'm learning, and It's been few days I've been stuck on this weather app project.
Since i'm new to APIs everything seems so complicated, I'm unable to get response properly from API And this time error I'm getting is "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"
My code for reference:
// navigator.geolocation.getCurrentPosition(pos=>{console.log(pos)});
async function getLoc(){
const apikeyloc = "//apikey//";
const locationapi = "http://dataservice.accuweather.com/locations/v1/cities/autocomplete"
let query = document.getElementById("location").value;
const inputbox = document.getElementById("location");
let locationList;
inputbox.addEventListener('keydown',async function(){
const api = fetch(`${locationapi}${apikeyloc}${query}`);
(await api).json().then(res=>{
console.log(res);
res.forEach(item => {
if (item.LocalizedName.indexOf(inputbox.value != -1)) {
locationList = `${item.LocalizedName},${item.AdministrativeArea.LocalizedName},${item.CountryLocalizedName}`;
console.log(locationList)
}
});
})
}
)
}
getLoc()
<!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>Weather app</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<Nav>
<div class="timezone">
<div class="city">CityName</div>
<div class="icon">icon</div>
</div>
<div class="search">
<input type="text" id="location" placeholder="Type Location...">
</div>
</Nav>
<div class="weather">
<div class="temprature">28deg</div>
<div class="wdesc">Today is Sunny</div>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
Any help would be appreciated.
You only assign the query variable once, to the document.elementById "location". This is empty at the loading of the page, so every api call you make in the keydown event will be with an empty query, resulting in a blank (non-json) response from the api.
Assign the query variable inside the key event. Also use keyup instead of keydown so that accessing the element's has the correct value. An ajax call on keyup should also be delayed, but take it one step at a time.
// navigator.geolocation.getCurrentPosition(pos=>{console.log(pos)});
async function getLoc(){
const apikeyloc = "?apikey=Om2MRV8SFRjSuVtjnisRhKGxTNQRzhrL&q=";
const locationapi = "http://dataservice.accuweather.com/locations/v1/cities/autocomplete"
const inputbox = document.getElementById("location");
let locationList;
inputbox.addEventListener('keyup',async function(){
//assign it here.
var query = document.getElementById("location").value;
const api = fetch(`${locationapi}${apikeyloc}${query}`);
(await api).json().then(res=>{
console.log(res);
res.forEach(item => {
if (item.LocalizedName.indexOf(inputbox.value != -1)) {
locationList = `${item.LocalizedName},${item.AdministrativeArea.LocalizedName},${item.CountryLocalizedName}`;
console.log(locationList)
}
});
})
}
)
}
getLoc()
<!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>Weather app</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<Nav>
<div class="timezone">
<div class="city">CityName</div>
<div class="icon">icon</div>
</div>
<div class="search">
<input type="text" id="location" placeholder="Type Location...">
</div>
</Nav>
<div class="weather">
<div class="temprature">28deg</div>
<div class="wdesc">Today is Sunny</div>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>

Cannot Read the property of addEventListener of null

I keep getting this error: Uncaught TypeError: Cannot read property 'addEventListener' of null. I looked at other posts that had similar issues but I guess my level of understanding for Javascript is not proficient enough to understand the proposed solutions given. Can someone help me?
Here is my Javascript code:
const multButton = document.getElementById('multiply');
const divideButton = document.getElementById('divide');
const firstNum = document.getElementById('firstNum')
const secondNum = document.getElementById('secondNum')
function multiplyNum(first, second){
const sum = first * second;
return alert(sum);
}
function divideNum(first, second){
const sum = first/second;
return alert(sum);
}
multButton.addEventListener('click', multiplyNum)
divideButton.addEventListener('click', divideNum)
Here is my HTML:
<!DOCTYPE html>
<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>Document</title>
</head>
<body>
Calculator
<div>
<form action="get">
1st Number: <input type="number" id="firstNum" name="firstNum"> <br>
2nd Number: <input type="number" id="secondNum" name="secondNum"> <br>
<button type="submit" id="multiply">Multiply</button>
<button type="submit" id="divide">Divide</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
What happens here is when you click on a button inside a form, it invokes the forms default submit method. I've moved the buttons outside the form tag so that it won't invoke the submit method. Thus we won't be redirected to another page on submission. Earlier we got redirected, that's why the dom elements where unavailable.
The HTMl:
<!DOCTYPE html>
<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>Document</title>
</head>
<body>
Calculator
<div>
<form action="get">
1st Number: <input type="number" id="firstNum" name="firstNum" /> <br />
2nd Number: <input type="number" id="secondNum" name="secondNum" />
<br />
</form>
<button id="multiply">Multiply</button>
<button id="divide">Divide</button>
</div>
<script src="script.js"></script>
</body>
</html>
The script
const multButton = document.getElementById("multiply");
const divideButton = document.getElementById("divide");
const firstNum = document.getElementById("firstNum");
const secondNum = document.getElementById("secondNum");
function multiplyNum() {
const sum = firstNum.value * secondNum.value;
return alert(sum);
}
function divideNum() {
const sum = firstNum.value / secondNum.value;
return alert(sum);
}
multButton.addEventListener("click", multiplyNum);
divideButton.addEventListener("click", divideNum);
Either multButton is null because an element with the "id" "multiply" doesn't exist or divideButton is null because an element with the "id" "divide" doesn't exist (or both don't exist).
Your code that you posted is fine (although in your form tag it should be method='get' and not action='get').
The following is a modified version of your code that I ran:
<!DOCTYPE html>
<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>Document</title>
</head>
<body>
Calculator
<div>
<form method='get'>
1st Number: <input type="number" id="firstNum" name="firstNum"> <br>
2nd Number: <input type="number" id="secondNum" name="secondNum"> <br>
<button type="submit" id="multiply">Multiply</button>
<button type="submit" id="divide">Divide</button>
</form>
</div>
<script>
const multButton = document.getElementById('multiply');
const divideButton = document.getElementById('divide');
const firstNum = document.getElementById('firstNum')
const secondNum = document.getElementById('secondNum')
multButton.addEventListener('click', function() {
alert('Multiply');
})
divideButton.addEventListener('click', function() {
alert('Divide');
})
</script>
</body>
</html>

Categories

Resources