简体   繁体   中英

Javascript: Display Image when radio button is clicked

I am currently working with radio buttons to display an image when clicked on with the help of javascript. The problem is that I am not getting result displayed when clicking a radio button. The code below shows that i am using a function and then triggering the even when click. Is there something the code is missing? or Is there a better approach to this? This an Example

Thank you

Javascript

<script>
    function check_value() {
        function check_value(fieldvalue) {
            switch (fieldvalue) {
            case 1:
                document.getElementById("imagedest").innerHTML = "<img src='images/bike1.jpg'>";
                break;
            case 2:
                document.getElementById("imagedest").innerHTML = "<img src='images/bike2.jpg'>";
                break;
            case 3:
                document.getElementById("imagedest").innerHTML = "<img src='images/bike3.jpg'>";
                break;
            }
        }
</script>

HTML

<form name="builder">
  <input type="radio" name="field" value="one" onclick='check_value(1)'/> KAWASAKI KX 450F<br />
  <input type="radio" name="field" value="two" onclick='check_value(2)'/> 2010 Yamaha Road Star S<br />
  <input type="radio" name="field" value="three" onclick='check_value(3)'/> Aprilia RSV4<br />
</form>


<div id="imagedest"></div>

What is the purpose of the extra function check_value() { preceding the code? It seems its purpose is to stop your code from working and therefore prompt you to ask this question.

Remove it, and all will be well.

function check_value() {
    function check_value(fieldvalue) {

That would be the problem. Take out the first line... You want just

function check_value(fieldvalue) {

In the future, check the console for errors, or put it into jsbin.com , it might give you more information on the issue. For your code, it tells you exactly what's wrong:

 Line 2: function check_value(fieldvalue) { --- 'check_value' is already defined. Line 1: function check_value() { --- Unmatched '{'. 

Personally ... I would load the images and then change the display settings, but if you don't want to do that..

Untested, edited in place:

<script>
    function check_value(val) { // You have to pass a parameter
       var imgs = ['images/bike1.jpg', 'images/bike2.jpg', 'images/bike3.jpg'];
       var img = imgs[val];
       var el = document.getElementById("imgBox");
       if (img) {
         el.src = img;
         el.style.display = "";
       }

     }
</script>

<img id="imgBox" src="#" style="display:none">

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