I want to change the backgroundImage of html with radio button selection. Every radio button has different image. I tried it like:
<input name="BG" id="wood" type="radio" value="" class="bgCollection" />
<label for="radio">Wood</label>
<input name="BG" id="steel" type="radio" class="bgCollection"/>
<label for="radio">Steel</label>
<input name="BG" id="metal" type="radio" value="" class="bgCollection"/>
<label for="radio">Black metal</label>
Jquery:
$(document).ready(function(){
$(".bgCollection").change(
function()
{
if($("input#wood").attr("checked"))
{$("html").css('backgroundImage','url(../images/wood.jpg)');}
if($("input#steel").attr("checked")
{$("html").css('backgroundImage','url(../images/BG-steel.jpg)');}
if($("input#metal").attr("checked"))
{$("html").css('backgroundImage','url(images/blackMetal.jpg)');}
});
});
But this way the background is not changing.
Here i have done complete demo for above issue. please check demo link.
Demo: http://codebins.com/bin/4ldqp80
HTML:
<input name="BG" id="wood" type="radio" value="" class="bgCollection" />
<label for="radio">
Wood
</label>
<input name="BG" id="steel" type="radio" class="bgCollection"/>
<label for="radio">
Steel
</label>
<input name="BG" id="metal" type="radio" value="" class="bgCollection"/>
<label for="radio">
Black metal
</label>
jQuery:
$(function() {
$(".bgCollection").change(function() {
if ($("#wood").is(":checked")) {
$("body").css('backgroundImage', "url('http://cdnimg.visualizeus.com/thumbs/7f/78/gfx,wood-7f78592c9a6ed3390492c560c5ac6fec_h.jpg')");
}
if ($("#steel").is(":checked")) {
$("body").css('backgroundImage', "url('http://www.aroorsteelcorporation.com/full-images/stainless-steel-834007.jpg')");
}
if ($("#metal").is(":checked")) {
$("body").css('backgroundImage', "url('http://i00.i.aliimg.com/photo/v0/468538622/Brushed_metal_texture_prepainted_metal.jpg')");
}
});
});
Demo: http://codebins.com/bin/4ldqp80
You are doing it right but you have a small syntax error in your jQuery
if($("input#steel").attr("checked")
Should be
if($("input#steel").attr("checked"))
Notice that missing bracket )
at the end
Working Fiddle
But a better way of doing will be using this to get the id and then apply switch to check the Value to set background
New Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With