Search code examples
javascripthtmlhref

How to change html output based on href directed from


If I have an html page(weeble.html) with two buttons, 'ButA' and 'ButB'. Selecting either bring you to the same html page (wobble.html), that contains two checkboxes, titled 'One' and 'Two' respectively. If you go to wobble.html through selecting ButA brings you there with the 'One' select box checked, and if you go there through ButB Two is selected. What methods do I use to do this? Forms? sessionStorage? php? Thanks for any explanation.


Solution

  • Since you tag only JS, here it is with that:

           function getQueryVariable(variable){
                var query = window.location.search.substring(1);
                if(query.split("&")){
                     var vars = query.split("&");
                }
                else{
                     var vars = query;
                }
                for (var i=0;i<vars.length;i++) {
                        var pair = vars[i].split("=");
                        if(pair[0] == variable){return pair[1];}
                }
                return("");
            }
            var selected = getQueryVariable('button');
            if(selected == 'A'){
                  document.getElementById('One').checked = true;
                  document.getElementById('Two').checked = false;
            }
            else if(selected == 'B'){
                  document.getElementById('One').checked = false;
                  document.getElementById('Two').checked = true;
            }
    

    Where your HTML on the weeble.html is:

    <a href="wobble.html?button=A"><button type="button" id="ButA" name="button_a">Select One</button><a/>
    
    <a href="wobble.html?button=B"><button type="button" id="ButB" name="button_b">Select Two</button><a/>
    

    And the HTML on wobble.html is:

    <input type="checkbox" name="one" id="One"><input type="checkbox" name="two" id="Two">
    

    To answer in English, set a query variable in the link based on which button is pressed and use JS to read in your query variable and check the input elements appropriately. There are better solutions than what's provided here, but I was trying to stay within what I assume is your current situation based on the question.