alimsuat alimsuat - 3 months ago 17
HTML Question

Change image attributes on listbox change using jquery

I want to display an album gallery that would be selected from selectbox for each separate folders.

the HTML code below:

<select name="album" id="album" onChange="changeimage();">
<option value="0" selected disabled>Select an album gallery...</option>
<option value="1">RC</option>
<option value="2">MR</option>
<option value="3">CD</option>
<option value="4">KP</option>
<option value="5">SH</option>
</select>

<!-- Display default images on page load -->
<img src="images/rC/img1.jpg" id="img1" title="RC" alt="Image1"/>
<img src="images/rC/img2.jpg" id="img2" title="RC" alt="Image2"/>
<img src="images/rC/img3.jpg" id="img3" title="RC" alt="Image3"/>
<img src="images/rC/img4.jpg" id="img4" title="RC" alt="Image4"/>
<img src="images/rC/img5.jpg" id="img5" title="RC" alt="Image5"/>


the jQuery code as below:

function changeimage() {
"use strict";
var folder;
var img_title;

if ($("select#album").val() === 1) {
folder = "rC/img"; img_title = "RC";
} else if ($("select#album").val() === 2) {
folder = "mR/img"; img_title = "MR";
} else if ($("select#album").val() === 3) {
folder = "cD/img"; img_title = "CD";
} else if ($("select#album").val() === 4) {
folder = "kP/img"; img_title = "KP";
} else if ($("select#album").val() === 5) {
folder = "sH/img"; img_title = "SH";
}

$("img#img1").attr({ src: "images/" + folder + "1.jpg", title: img_title, alt: "Image1" });
$("img#img2").attr({ src: "images/" + folder + "2.jpg", title: img_title, alt: "Image2" });
$("img#img3").attr({ src: "images/" + folder + "3.jpg", title: img_title, alt: "Image3" });
$("img#img4").attr({ src: "images/" + folder + "4.jpg", title: img_title, alt: "Image4" });
$("img#img5").attr({ src: "images/" + folder + "5.jpg", title: img_title, alt: "Image5" });
}


So, where did I have mistake? Thanks...

Answer

Jquery .val() return content of value attribute of selected option that is string. Problem of your code is in condition.

if ($("select#album").val() === 1)

When you used === in if condition that means should type of values be equal. While 1 isn't equal to "1". You need to use

if ($("select#album").val() === "1")
// or
if ($("select#album").val() == 1)