How do I get the id present in the link using jQuery? - javascript

I am calling data from a movie API using jquery and it has an endpoint where I can call a particular show with an id. The home page displays the movies and clicking them should call another endpoint of the API. Below is my code:
$(function (){
let $movies = $('#showList')
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows',
success: function(movies){
$('#show').hide()
$('#showList').removeAttr('hidden');
$.each(movies, function(i,movie){
$movies.append('<li class="list"><a id="ss" href="'+ movie._links.self.href+'">'+ movie.name +'</a></li>')
})
}
})
})
$('body').on('click','.list a',function(event){
event.preventDefault();
$('#showList').hide();
$('#show').empty()
let currentId = event.target.id;
console.log(currentId)
$.ajax({
method:'GET',
url:'http://api.tvmaze.com/shows/'+currentId,
success: function(movies){
$('#show').append('<h1>'+ movies.name +'</h1>')
}
})
$('#show').show();
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">
<title>TV Shows</title>
</head>
<body>
<h1>TV Shows</h1>
<div id="show" hidden></div>
<ul id="showList" hidden></ul>
<form id="searchForm">
<input type="text" id="search_term">
<label for="text">Search</label>
<button>Submit</button>
</form>
<a id="homelink" href="/" hidden>Back to All Shows</a>
<footer>Swayam Shah, 10471353</footer>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="/public/js/index.js"></script>
</body>
</html>
How do I get this id when I click on the movies link? The console.log shows empty.

you haven't mentioned id attribute in your anchor tag.
$movies.append('<li class="list">'+ movie.name +'</li>')

Had to replace URL with only currentID

Using "this" works for me.
$("a").click(function() {
console.log($(this).attr("id"));
});

Related

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 let onClick() read from my javascript file?

I have two files index.html and index.js. When I fill the text fields in the form and click the button, it should redirect to index.js. How do I achieve that?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
<script src="index.js"></script>
</body>
</html>
index.js
if (document.getElementById("email").nodeValue==document.getElementById("pass").nodeValue){
alert("You are allowed");
}
EDIT: I can do this simply by creating the function inside the <script> tag itself and then calling the function inside onClick in the <button> tag. But instead, I want the onClick to call my index.js script which will perform the backend stuff
declare this function in index.js
function handleClick() {
if (
document.getElementById('email').nodeValue ===
document.getElementById('pass').nodeValue
) {
alert('You are allowed');
}
}
call it on button click
<button onclick="handleClick()">Click</button>
you should link the html file to the javascript file using
<script type="text/javascript" src="(your file location)"></script>
then add event listeners to listen to the button click using
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("button-id").addEventListener('click', yourFunction)
});
function yourFunction(){
//your code here
}
also add an id to the button so you can add the event listener to it
<button id="button-id">Click</button>
You need to use EventListener to bind button click event to a function.
document.getElementsByTagName('button')[0].addEventListener('click',function(){
if (document.getElementById("email").value==document.getElementById("pass").value){
alert("You are allowed");
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
</body>
</html>
you should add the js file in your index.html
<script type="text/javascript" src="index.js"></script>
then you should add onclick event on your button
<button onclick="myFunction()">Click</button>
then in index.js you should add the function
function myFunction(){
//your logic goes here
}
Always call your script inside js only. It is bad practice to call scripts in the html structure. I gave you an example of calling script logic and accessing a component using querySelector().
var form_button = document.querySelector('.thisisbutton');
var email_input = document.querySelector("#email");
var pass_input = document.querySelector("#pass");
form_button.onclick = function() {
if (email_input.value == pass_input.value){
alert("You are allowed");
}
}
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email">
<br><br>
<input type="password" id="pass">
<br><br>
<button class="thisisbutton">Click</button>
</body>

jQuery get function doesn't work as expected

I need to get photos using GIPHY API, I have the following function:
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="submit" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>
So, the problem is that $.get() function doesn't respond at all, even always() callback function does not get executed.
When I try this particular URL in the Postman application, I get the response (json object) and I can access the data.images.origianl.url property it is there.
When I try the following line of code in the console :$.get("https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1"); I get the response with the status code 200, so it should work in the main.js file, but in my case it doesn't.
I have two variables url1 and url2 this is because, in my first tries I did not get anything with the url1, but getting the success with the url2. After some time I didn't get anything using two of them.
What is the problem? How can it be that I can get responses from Postman and from the console using the same URLs, but do not get them with actual code?
Thank you for your patience!
This is a common problem, understanding the difference between type button and type submit.
Submit will submit the form. Whereas button will just process the event handlers assigned.
Change
<input type="submit"
to
<input type="button"
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="button" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>

Chat not closing and not showing response

I made a qnamaker service and build a chat to show the response of the question.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Chat</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="chat.js"></script>
<script src="rispostachat.js"></script>
<link rel="stylesheet" href="chat.css">
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="live-chat">
<header class="clearfix">
x
<h4>Bot</h4>
</header>
<div class="chat">
<h3>Risposta:</h3>
<div id="answer"></div>
<input type="text" id="question" name="question">
<button type="button" class="button" id="post-btn"> Chiedi</button>
</br>
</body>
</html>
This is for close and show the chat box
(function() {
$('#live-chat header').on('click', function() {
$('.chat').slideToggle(300, 'swing');
});
$('.chat-close').on('click', function(e) {
e.preventDefault();
$('#live-chat').fadeOut(300);
});
}) ();
And this is for take the response inserted and show the response to the user
$("#post-btn").click(function(){
jQuery.ajax ({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/idknowledgebasetoinsert/generateAnswer",
type: "POST",
data: '{"question" : "'+$("#question").val()+'"}',
dataType: "json",
contentType : "application/json",
headers: {"Ocp-Apim-Subscription-Key": "subscriptionkeytoinsert"},
success: function(msg, status, jqXHR){
$('#answer').html(msg.answers[0].answer);
}
});
});
When i click on the header of the chat , the chat not close and the chat not disappear when i clcik on the close button x of the chat.
When i click on Chiedi to send the answer nothing happen. I don't see the response of the service in the chat.
it looks like you have included the jQuery twice (2 different versions) in your header
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="jquery-3.3.1.min.js"></script>

Cannot set property innerHTML error

I am trying to automate the process of opening an external site from a button of an internal site that I created, but I can not reference the document I created, follow the code below, tried several times and could not, any help is valid, thank you so much.
<!DOCTYPE html>
<head>
<title>Principal</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="\\fswcorp\ceic\ssoa\gaacc\System\JQuery\jquery-3.2.1.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryMask\dist\jquery.mask.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryUI\jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#dateBegin").mask('00/00/0000');
$("#dateEnd").mask('00/00/0000');
$("#buttonDownloadBRScan").click(function() {
$windowopen = window.open();
$windowopen.location.href = "https://www.fdibr.com.br/autenticacao/autenticacao/login";
$test = $windowopen.document.getElementById("usuario").innerHTML = "7478704";
})
});
</script>
</head>
<body>
<div class="dataInput">
<label id="labelDateBegin">Data Inicial</label>
<input id="dateBegin" type="date" />
<label id="labelDateEnd">Data Final</label>
<input id="dateEnd" type="date" />
</div>
<br><br>
<button id="buttonDownload">Download</button>
<button id="buttonDownloadBRScan">Download BRScan</button>
</body>
Assuming you have access to that domain in the window you're opening (same origin policy), you have to wait for the window to finish opening first before accessing elements inside.
$("#buttonDownloadBRScan").click(function(){
const w = window.open('https://www.fdibr.com.br/autenticacao/autenticacao/login');
w.addEventListener('DOMContentLoaded', () => {
w.document.getElementById("usuario").innerHTML = "7478704";
});
})
Try something like this:
<input id="yourID" type="button" onclick="open_page()" value="Your Message Here"/>
<script>
function open_page () {
window.open('Your Webpage');
}
</script>
the external site and your internal site have different domain,you can't modify the external site content from your internal site directly.you can use window.postMessage,maybe it would resolve your problem

Categories

Resources