简体   繁体   中英

I have an option form and I would like to show a different image from a JSON file for each element of the option tag i choose

so I created an option form and at the bottom of this I have a div where i want to show images taken from a JSON file based on which voice of the option form i select. To be more specific, I'll write some code down here:

HTML:

<select name="classes">
  <option value="knight">Knight</option>
  <option value="mage">Mage</option>
  <option value="priest">Priest</option>
</select>

JS:

const classes = [
    {
        id: 1,
        class: "knight",
        male: "../class-png/male-knight.png",
        female:"../class-png/female-knight.png"
    },
    {
        id:2,
        class:"mage",
        male:"../class-png/male-mage.png",
        female:"../class-png/female-mage.png"
    },
    {
        id: 3,
        class: "priest",
        male: "../class-png/male-priest.png",
        female:"../class-png/female-priest.png",
    }
];

So if i select the "knight" option, i want to show the two png of the knights inside a div below and so on for the mage. . .
I would to do this using the id of the JSON objects

Your html will be like this

<select class="classes" name="classes">
   <option value="knight">Knight</option>
   <option value="mage">Mage</option>
   <option value="priest">Priest</option>
</select>
<div id="imageWrapper"></div>

Here is your jquery code based on your selected option value

<script>
    let selectedClass = "knight";
    const classes = [
    {
        id: 1,
        class: "knight",
        male: "../class-png/male-knight.png",
        female:"../class-png/female-knight.png"
    },
    {
        id:2,
        class:"mage",
        male:"../class-png/male-mage.png",
        female:"../class-png/female-mage.png"
    },
    {
        id: 3,
        class: "priest",
        male: "../class-png/male-priest.png",
        female:"../class-png/female-priest.png",
    }
];
// To load Images for pre-selected option
addImage();
$(document).ready(() => {
    $(".classes").change(() => {
        $("#imageWrapper").empty();
        selectedClass = $('.classes :selected').val();
        // change image on option change
        addImage();
    })
})
function addImage (){
    $.each(classes, function( index, value ) {
        if(value.class == selectedClass){
            $("#imageWrapper").prepend('<img id="image" src="'+value.male+'" /><img id="image" src="'+value.female+'" />')
        }
    });
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM