Reputation: 163
I have a image with the css class .normalImage
I made 3 radio buttons and when the user select 1 of the radio buttons the style of the image must change to .blackImage
or .sepiaImage
I have 3 radio buttons, each must activate a new style to the image :
<input type="radio" name="color" value="grijs">Black<br>
<input type="radio" name="color" value="sepia">Sepia<br>
<input type="radio" name="color" value="normal">Normaal<br>
How can i change the style of the image when someone checks one of the radio buttons?
Upvotes: 4
Views: 8399
Reputation: 863
There is a better way to change the class; rather than removing then adding a new class, you could use the jQuery switchClass()
function.
Like this:
var $img = $("#myImage");
$('input[name=color]').on('change', function()
{
$img.switchClass($img.attr('class'), $(this).val());
});
Upvotes: 0
Reputation: 8161
You can use .addClass()
method
Try this :
$('input[type=radio]').change(function() {
$("img").removeClass();
if($(this).val() == "grijs"){
$('img').addClass('blackImage');
}
else if($(this).val() == "sepia"){
$('img').addClass('sepiaImage');
}
else if($(this).val() == "normal"){
$('img').addClass('normalImage');
}
});
Upvotes: 1
Reputation: 12300
jQuery:
var $img = $("#myImage");
$('input[name=color]').on('change', function() {
$img.removeClass().addClass($(this).val());
});
HTML:
<p id="myImage">Text instead of an image</p>
<input type="radio" name="color" value="grijs">Black<br>
<input type="radio" name="color" value="sepia">Sepia<br>
<input type="radio" name="color" value="normal">Normaal<br>
CSS:
.grijs {
color: red;
}
.sepia {
color: blue;
}
.normal {
color: green;
}
Upvotes: 0
Reputation: 1
I think you need to handle radio button .change() event and check for selected and deselected. After that use .removeClass() and .addClass() methods.
Upvotes: 0
Reputation: 572
You can use, addClass()
<script type="text/javascript">
if ("input[type='radio']")
{
$(this).addClass("newclass");
}
</script>
if you wish to remove the previous class then you can use:
if ("input[type='radio']")
{
$(this).removeClass().addClass("newclass");
}
Upvotes: 0
Reputation: 7352
you can add a click function with parameter off the css class.
function setCssClass(className){
$("#IMAGE_ID").addClass(className);
}
<input type="radio" name="color" value="grijsImage" onclick="setCssClass('grijs');">Black<br>
<input type="radio" name="color" value="sepiaImage" onclick="setCssClass('sepiaImage');">Sepia<br>
<input type="radio" name="color" value="normal"onclick="setCssClass('normal');">Normaal<br>
Upvotes: 0
Reputation: 645
Is that what you are looking for?
$('input[name=color]').on('click', function() {
$('#my-image').removeClass().addClass( $(this).val()+"Image" );
});
Upvotes: 0