so what i'm trying to do is: When you select a grade , a function will be triggered and output the book covers (images of the book covers) of the selected grade.
const select = document.querySelector('#my');
const img = document.querySelectorAll('img');
select.addEventListener('change', e => {
const gradeString = e.target.value;
const url = `history covers/grade${gradeString}.jpeg`;
// images in array so i need to loop through all of the imgs and update each one at a time
img.src = url;
img.alt = `grade${gradeString}`;
})
<p>Select your grade from the list.</p>
<p>When you select a grade, a function is triggered which outputs the book covers of the selected grade.</p>
<select id="my">
<option value="all">All Grades</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="3">Grade 3</option>
<option value="4">Grade 4</option>
<option value="5">Grade 5</option>
<option value="6">Grade 6</option>
<option value="7">Grade 7</option>
<option value="8">Grade 8</option>
</select>
<img src="history covers/grade6-dor.jpeg">
<img src="history covers/grade8.jpeg">
<img src="history covers/grade7.jpeg">
<img src="history covers/grade6-mahavak.jpeg">
CodePudding user response:
add all your images to your html and set the css to display none. Then in your js just change the style to block for the image you want. That image will be your gradeString - 1
const select = document.querySelector('#my');
const img = document.querySelectorAll('img');
select.addEventListener('change', e => {
const gradeString = e.target.value;
img[gradeString-1].style.display='block'
})
.images{
display:none;
}
<p>Select your grade from the list.</p>
<p>When you select a grade, a function is triggered which outputs the book covers of the selected grade.</p>
<select id="my">
<option value="all">All Grades</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="3">Grade 3</option>
<option value="4">Grade 4</option>
<option value="5">Grade 5</option>
<option value="6">Grade 6</option>
<option value="7">Grade 7</option>
<option value="8">Grade 8</option>
</select>
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
<img class='images' src="https://via.placeholder.com/150">
CodePudding user response:
^^^ Thanks for replying. That code I know and tried. but notice that the defualt needs to be all of the book covers. pay attention to the name of the images I chose. i have 2 images named grade6-...(and more text), one image named grade7, and another image named grade 8. when i select on the site grade 2 for example it shows me the images of grade7&grade8
