jQuery: Help with <Select> Form
Here's what I have:
<select id="barrelSelect">
<option value="barrelDefaultOption">-- Choose --</option>
<option value="blackBarrel" rel="10">Black Barrel</option>
<option value="blueBarrel" rel="25">Blue Barrel</option>
<option value="greenBarrel" rel="30">Green Barrel</option>
</select>
<select id="slideSelect">
<option value="slideDefaultOption">-- Choose --</option>
<option value="blueSlide" rel="15">Blue Slide</option>
<option value="blackSlide" rel="45">Black Slide</option>
<option 开发者_StackOverflow中文版value="greenSlide" rel="50">Green Slide</option>
</select>
<p>$ <span id="output"></span> </p>
<script>
function onSelectChange(){
var total = 0,
barrel = $("#barrelSelect").find('option:selected'),
slide = $("#slideSelect").find('option:selected');
if(value = barrel.attr('rel')){
total += parseInt(value);
}
if(value = slide.attr('rel')){
total += parseInt(value);
}
$("#output").html(total);
}
$("#barrelSelect").change(onSelectChange);
$("#slideSelect").change(onSelectChange);
</script>
Viewable here: http://jsfiddle.net/A5VEv/1/
I'd like to add functionality to the script so that when a user chooses an option - a default image associated with that option changes.
For Example:
<div id="defaultImage"><img src="default.jpg" /></div>
So how can I alter the code so when a user selects "blue barrel", the default image changes to bluebarrel.jpg?
Also, want to give credit to http://jsfiddle.net/mekwall/TJcP4/1/ for the original select menu code.
You need to have some way to map the select option values to image names. if you say that the image names will always be the lower case value of the selected option, and always a jpeg you could easily do:
$('#defaultImage img').attr('src', dermal.val().toLowerCase() + '.jpg');
You might have to do some other work in order to map your images if they don't fit that pattern. Good luck.
The quickest way to change the image is with a bit of jquery, along the lines of
$('#defaultImage img').attr('src', 'newImageLocation.jpg')
You didn't specify how the name of the image was going to be obtained but assuming it's going to be the value of option
followed by .png
, you might do it as shown in this fiddle: http://jsfiddle.net/nogoodatcoding/A5VEv/4/
The jQuery line behind this is simply:
$('#defaultImage img').attr('src', barrel.val() + '.png');
Also note that you can simplify your code to get the currently selected option to just:
barrel = $('#barrelSelect :selected'),
slide = $('#slideSelect :selected');
Name your images "optionValue.jpg", and do this :
$(document).ready(function() {
$('#barrelSelect').change(function(){
$('#barrelImage').attr('src', 'path/to/' + $(this).val() + '.jpg');
});
});
Where #barrelImg is the img tag for your barrel
精彩评论