简体   繁体   中英

How to display different content when a user selects a radio button?

I want make one feature. HTML/PHP is no problem, but my JavaScript skill is really low. I know how to use it, but I don't know how to write such a thing. It should look like this example.

Under the picture, there's something called a "MILESTONE" - but in this case, the action is onhover . I want to use the onclick event and a set of radio buttons. When the user clicks on one of the three radio buttons, the page will change the picture and the description, depending on which one was clicked - and without refreshing the page.

I don't really get how it works, but if each option were one single page and I could just include them all, it would be ideal.

If your skills are good enough in HTML & CSS then you will know how to style it properly. Here is a sample code I have just done that has the JavaScript (functionality).

Live example: http://embed.plnkr.co/xdpHX9FplgLgh9pN7lWZ/preview

Explanation:

You will have the following HTML markup:

<div id="controls">
  <input type="radio" name="slide" value="slide1.html"> 1
  <input type="radio" name="slide" value="slide2.html"> 2
  <input type="radio" name="slide" value="slide3.html"> 3
</div>

And you will have the following JavaScrit using jQuery:

$(function(){
  $('#controls').on('click', ':radio', function(e) {
    var target = $(e.target);
    $.get(target.val(), function(data) {
      $('#content').html(data);
    });
  });
});

Basically, the JavaScript (using jQuery) will do the following: after clicking a radio button the <div id="controls" /> 's content will be replaced with the content of the file specified in the radio button value attribute.

Your question is fairly broad, so I'm going to focus on the task of swapping visible content on a fired event.

Writing this in jQuery, but you should be able to translate it if you're not using JQ:

HTML:

<input type="radio" name="picker" class="picker" value="1"/>
<input type="radio" name="picker" class="picker" value="2"/>
<input type="radio" name="picker" class="picker" value="3"/>

<ul class="content">
  <li><img src="foo1"/></li>
  <li><img src="foo2"/></li>
  <li><img src="foo3"/></li>
</ul>

CSS:

.content li { display: none; }
.content li.active { display: block; }

JavaScript:

$('.picker').on('click', function() {
  $('.content .active').removeClass('active');
  $('.content li').eq($(this).val() - 1).addClass('active');
});

Working example: http://jsfiddle.net/9SdvZ/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM