Im building a random DogAPI image generator, where you put a number from 1-50 into a form text box, and hit send, and it returns the number you input into (linked) images printed to the console. I can manually put the number at the end of fetch, and it prints that amount to the console, but I'm having trouble connecting the number you put in your form to put it on the end of your fetch request.
Ive tried using template literals. If you manually type ${5} at the end of fetch, it prints 5 images to console. Great! But... how do I use Template Literals to connect what I put in the form to the end of the fetch. ${text} obviously doesn't work! Or am I doing it all wrong? Thanks for your help everyone!
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>How Many?</title>
<link rel="shortcut icon" href="#">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>How Many Dog Pics Do You Want?</h1>
<form>
<input type="text" placeholder="1-50?">
<input type ="submit" value="Send">
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
CSS:
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
JS:
'use strict';
function getDogImage() {
fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
.then(response => response.json())
.then(responseJson => console.log(responseJson));
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
getDogImage();
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
You need to get the value from the input (using .val()
), and pass it to getDogImage(text)
(see comments in code):
function getDogImage(text) { // add the text parameter
fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
.then(response => response.json())
.then(responseJson => console.log(responseJson));
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
var text = $('.number').val() || 3; // get the text from the input or use 3
getDogImage(text); // pass to getDogImage
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h1>How Many Dog Pics Do You Want?</h1>
<form>
<input class="number" type="text" placeholder="1-50?">
<input type="submit" value="Send">
</form>
</div>