Reputation: 111
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.
Upvotes: 5
Views: 5394
Reputation: 9131
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
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
Upvotes: 2
Reputation: 9080
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
Upvotes: 2
Reputation: 2150
There is ) missing in the following line of your code:
if($("input#steel").attr("checked"))
{$("html").css('backgroundImage','url(../images/BG-steel.jpg)');}
Upvotes: 0
Reputation: 40639
First problem in your code
Your second if conditions is wrong if($("input#steel").attr("checked")
It should be if($("input#steel").attr("checked"))
your closed parenthesis is absent here
then one more thing you should change only the next label means control not the whole html.
So use .next()
function of jquery Documentation here http://api.jquery.com/next/
I tried this code on jsfiddle test here: http://jsfiddle.net/FB37y/
Upvotes: 0