Using jQuery to Toggle Images with Radio Buttons

Here’s a simple example to toggle Images using Radio Buttons:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Toggle Images using RadioButtons</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(document).ready(function() {
$("input:radio[name=rdImg]").change(function() {
if (this.value == "0") {
$("#imgOne").attr(
'src', 'http://theimagepathcomeshere.jpg'
);
}
else {
$("#imgOne").attr(
'src', 'http://thesecondimagepathcomeshere.jpg'
);
}
});
});
</script>
</
head>
<
body>
<
label><input name="rdImg" type="radio" value="0" />Image 1</label><br />
<
label><input name="rdImg" type="radio" value="1" />Image 2</label><br />
<
img id="imgOne" />
</
body>
</
html>

Similarly you can add multiple radio buttons and toggle multiple images with it.

Just use the value of each radiobutton to toggle the right image.

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: