开发者

How do I toggle two images using jQuery and radio buttons?

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.j开发者_StackOverflowpg',
                 alt: 'one dot jpg'
        });
    }
    else {
            $('#showjpg').attr({
                 src: 'two.jpg',
                 alt: 'two dot jpg'
        });
    }
});


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.


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.


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*/});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜