I am writing a front-end code for a website using jQuery and AJAX and Handlebars.js. I have HTML,CSS and script.js files. I am pretty new to Javascript and techniques. This is the first time i'm using Handlebars in my code.
I used JSON parsing to parse through the entire data provided in a URL. It's
something like
{"products":
[{"id": 0,
"name": "Ocean Blue Shirt",
"description": "<p>Ocean blue cotton shirt with a narrow collar and
buttons down the front and long sleeves. Comfortable
fit and tiled kalidoscope patterns. </p>",
"category": "men",
"image_url": "https://burst.shopifycdn.com/photos/young-man-in-bright-
fashion_925x.jpg",
"unit_cost": 92.95,
"inventory": 0},
{"id": 1,
"name": "Classic Varsity Top",
"description": "<p>Womens casual ......}
..
..
]}
I have created buttons and used {{name}} to create multiple buttons with iterated names. My objective is to make each button contain their respective {{description}} in a 'modal' view, when i click on them.
I have been able to achieve one the first button ( named by using {{name}} ) displaying its description starting from 'Ocean blue cott.....' when i click on it, however, i am not able to get anything if i click any other buttons( with other {{name}}s.
Kindly look at the code and help me figure out what's wrong, thanks!
script.js
var myRequest = new XMLHttpRequest()
myRequest.open('GET' , 'http://127.0.0.1:8010/products' )
myRequest.onload = function() {
var myData = JSON.parse(myRequest.responseText)
createHTML(myData)
// Get the modal
var modal = document.getElementById("myModal")
// Get the button that opens the modal
var btn = document.getElementById("myBtn")
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0]
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block"
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none"
}
}
myRequest.send()
function createHTML(data) {
var template = document.getElementById("prodTemp").innerHTML
var compiledTemplate = Handlebars.compile(template)
var genHTML = compiledTemplate(data)
var prodContainer = document.getElementById("prod-container")
prodContainer.innerHTML = genHTML
}
index.html
{{#each products}}
<tr>
<td>
<!-- Trigger/Open The Modal -->
<button id="myBtn">{{name}}</button>
<!-- The Modal -->
<div class = "modal" id="myModal" >
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<li >Product Description: {{{description}}}</li>
</div>
</div>
</td>
<td>
${{unit_cost}}
</td>
</tr>
{{/each}}