Home > Net >  Javascript SetForm via parameter in url
Javascript SetForm via parameter in url

Time:10-06

I try to change the SetForm by a parameter in my url like radio.php?land=form2. But it won't works. It does work manually via the menu.

Its my first time i try javascript.

Hopefully some one can help. Thank you.

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const setForm = urlParams.get('land')
function setForm(value) {

    if(value == 'form1'){
                document.getElementById('form1').style='display:block;';
                document.getElementById('form2').style='display:none;';
            }
            else if(value == 'form2'){

                document.getElementById('form2').style = 'display:block;';
                document.getElementById('form1').style = 'display:none;';
            }

}
<select id="select1" onchange="setForm(this.value)" class="btn btn-secondary">
<option value="form1">Nederland</option>
<option value="form2">Frankrijk</option>
</select>

<div id="form1">
Nederland
</div>
<div  id="form2" style="display: none">
Frankrijk
</div>

CodePudding user response:

You'll have to make some change to get this working:

  • Move the first time query param based selection under window.onload so we run it once the DOM is clean.
  • Change the variable name associated with value urlParams.get('land') to something else. Here I changed it to land
  • Call the setForm method with the land so the page is initialized.

   window.onload = function () {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const land = urlParams.get('land'); // get the value
    setForm(land); // set it here
}
function setForm(value) {
    document.getElementById('select1').value = value; // if you want to update the dropdown value as well
    if(value == 'form1'){
        document.getElementById('form1').style='display:block;';
        document.getElementById('form2').style='display:none;';
    }
    else if(value == 'form2'){
        document.getElementById('form2').style = 'display:block;';
        document.getElementById('form1').style = 'display:none;';
    }

}
<select id="select1" onchange="setForm(this.value)" class="btn btn-secondary">
<option value="form1">Nederland</option>
<option value="form2">Frankrijk</option>
</select>

<div id="form1">
Nederland
</div>
<div  id="form2" style="display: none">
Frankrijk
</div>

  • Related