Search code examples
javascriptphphtmlcssdropdown

Making dropdown value and image active on another page by clicking from another page


I dont know whether its possible or not. In a project I want whereas on page 1 all products are there with different flavour on page 2 is a descriptive page for it. So once i click on a particular product on page 1 the same product is active on page 2 in its dropdown and image also.

Page 1

<div class="m-t text-center">
    <a href="" class="btn btn-xs btn-outline btn-primary">Chocolate <i
            class="fa fa-long-arrow-right"></i> </a>
</div>

<div class="m-t text-center mt-3" >
    <a href="" class="btn btn-xs btn-outline btn-primary">Cafe <i
            class="fa fa-long-arrow-right"></i> </a>
</div>

<div class="m-t text-center mt-3" >
    <a href="" class="btn btn-xs btn-outline btn-primary">Cream and cookies <i
            class="fa fa-long-arrow-right"></i> </a>
</div>

Page 2

<img id="img1" src="img/tryimages/WHEYPRO-FRONT-1.png" name="myImage">


<div class="mt-3">
    <form method="" action="" name="flavours">
        <select  name="switch" onchange="switchImage();">
            <option value="1" id="chocolate">Chocolate</option>
            <option value="2" id="cafe">Cafe</option>
            <option value="3" id="cc">Cream & Cookies</option>
        </select>
    </form>
</div>

<script>
    // This is the code to preload the images
    var imageList = Array();
    for (var i = 1; i <= 3; i++) {
        imageList[i] = new Image;
        imageList[i].src = "img/tryimages/WHEYPRO-FRONT-" + i + ".png";
    }

    function switchImage() {
        var selectedImage = document.flavours.switch.options[document.flavours.switch.selectedIndex].value;
        document.myImage.src = imageList[selectedImage].src;
    }
</script>

So like if anybody click on cafe button on page 1 the same image and the dropdown value should be active on page 2 and so on. If its possible on Javascript or Php kindly help as I am bit new to programming.

Thanks


Solution

  • You could do this with two methods

    First: By sending query parameter to second page i.e you could send the value of items to second page

    In page 1:

    <a href="link-to-page-2?i=1" class="btn btn-xs btn-outline btn-primary">Chocolate <i
                class="fa fa-long-arrow-right"></i> </a>
    

    And in page 2 you can access this parameter:

    
            <script>
                let selectedImage = 0;
                window.addEventListener("load", (e) => {
                    let searchParams = new URLSearchParams(window.location.search);
                    if (searchParams.has("i")) {
                        selectedImage = searchParams.get("i");
                        // run the switchImage function then.
                    }
                });
    
            </script>
    

    Second: You could use the localstorage. You could store the index in localstorage and access it in another page.