views:

44

answers:

3

This isn't pretty, but I think you'll get what I'm trying to do.

<label><input name="jpgSel" type="radio" value="0">jpg 1</label><br />
<label><input name="jpgSel" type="radio" value="1">jpg 2</label><br />
<div id="showjpg"></div>

and

$(document).ready(function() {
    $("select").change(function () {
           if ($("jpgSel:checked").val() == 1) {
            $('#showjpg').attr({
                src: 'one.jpg',
                 alt: 'one dot jpg'
        });
    }
    else {
            $('#showjpg').attr({
                 src: 'two.jpg',
                 alt: 'two dot jpg'
        });
    }
});
+1  A: 
if ($("jpgSel:checked").val() == 1) {

should read

if ($("#jpgSel:checked").val() == 1) {

or was that a typo?

Also you may want to use $('#jpgSel:checked') on its own w/out == 1

edit

oh and $("input[@name='jpgSel']").click(function(){ might be better.

griegs
You don't need the `@` anymore, nor the single quotes. So `$("input[name=jpgSel]")...` should do it.
Ken Redler
Thanks for this.
trench
A: 

You have several issues:

  • The #showjpg element is a div, you should have there an img element.
  • The selector you are using to bind the change event is incorrect ($("select")), it should be something like $("input[name=jpgSel]")
  • If you bind the change event to both radio buttons, you can get the value of the selected element simply by this.value.

Try this:

$(document).ready(function() {
  $("input[name=jpgSel]").change(function () {
    if (this.value == "0") {
      $('#showjpg').attr({
        src: 'one.jpg',
        alt: 'one dot jpg'
      });
    } else {
      $('#showjpg').attr({
        src: 'two.jpg',
        alt: 'two dot jpg'
      });
    }
  });
});

Check an example here.

CMS
Thanks! Exactly what I was looking for. And thoroughly explained. Seriously, thank you.
trench
A: 

jpgSel is a name and has to be selected like this

$("[name='jpgSel']:checked") 

although i think it would be easier to scrap that and use the .click() function like so

$("[name='jpgSel'][value='0']").click(function{/*do something*/});
$("[name='jpgSel'][value='1']").click(function{/*do something else*/});
Greg Guida