user983248
user983248

Reputation: 2688

if else on javascript with the value of a select box (pure javascript)

I'm working on a select box that have images instead of text, (on the background with css).

<script type="text/javascript">
function onChange(element) {
element.style.backgroundColor = "Yellow";
element.className = "on_change";
}
</script>



<select onchange="onChange(this);">
<option value="1" style="background: url(/one.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option>
<option value="2" style="background: url(/two.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option>
<option value="3" style="background: url(/three.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option>
</select>

The problem is how do I get the value of the selected option and if is 1 set one image and if it is two set another image as the background using pure javascript (no jQuery)?

I know that selectedIndex is the key to my problem, but I'm clueless of how to use it or how to use it on an if else statement.

The script above is just one of my trials, I actually use the script above to perform the same task.

<select onchange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor; this.style.color=this.options[this.selectedIndex].style.color">

Upvotes: 1

Views: 2217

Answers (1)

gaurang171
gaurang171

Reputation: 9080

Here is working example. http://codebins.com/codes/home/4ldqpb9

you dont need if else but just change background image based on selectedIndex.

function onChange(obj) {
    obj.style.backgroundImage = obj.options[obj.selectedIndex].style.backgroundImage
}

Upvotes: 1

Related Questions