简体   繁体   中英

JS: output inconsistencies

This code gets the user input and substitute it to "selected", Example

1st Input
User Input:

Apple

Process(what happens inside):

"img2/" + Apple + ".jpg";

Output:

Apple.jpg (image)

The problem is once the user inputs a query that doesn't have the corresponding image the code, outputs the previous one

2nd Input User Input:

Orange

Process(what happens inside):

"img2/" + Apple + ".jpg";

Output:

Apple.jpg (image) //wrong incorrect

 var q = document.getElementById("code");


if (q.selectedIndex > 0) { 

var selected = q.options[q.selectedIndex].value;
var src = "img2/" + selected + ".jpg";
var img = document.getElementById("placeholderImg");
img.src = src;
img.style.display = "inline";

}

<select name="code" id="code" size="" disabled="true" hidden="true">
<option value="Apple">Apple</option>
<option value="Atis">Atis</option>
//so on and so forth

how can I fix this? any suggestion opinion is highly appreciated

Your mistake lays within the line

if (q.selectedIndex > 0)

The selectedIndex property is 0 when the first row is selected (in your case "Apple"). Therefor this if statement will only work if something else than "Apple" is selected.
The selectedIndex property is -1 when nothing is selected, not 0 !

You should replace it with the following statement:

if (q.selectedIndex > -1)

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