Home > Enterprise >  Pre-select a dropdown in a form from an external URL link
Pre-select a dropdown in a form from an external URL link

Time:12-08

I have this form, and I can't change anything about it (ids, vals, etc) because its auto generated by my website builder. Is it possible to use code or even better, just use the URL to auto select an option? For example, use the URL

https://mywebsite.com/GCValue=50/

to select the 50 option in the form below, instead of the 10 that it will default on? I'm a beginner with JS and JQuery, so I'm happy to use those and learn a little bit about it during the process, if its possible.

<select id=GCValue>
  <option val="10">10</option>
  <option val="25">25</option>
  <option val="50">50</option>
  <option val="100">100</option>
  <option val="250">250</option>
</select> <br />

Any help or external links pointing me in the right direction appreciated.

CodePudding user response:

Using Just One Variable from JS Document Pathname

Use window.location.pathname to get the path of the current page, then use a simple regex.exec(url) to capture anything that matches /=([0-9]) /. This will match anything in the format of "=12345", and return "12345" as the match.

var url = "https://mywebsite.com/GCValue=50/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /=([0-9] )/g;
var match = regex.exec(url);
document.getElementById("GCValue").value = match[1];
<select id="GCValue">
  <option val="10">10</option>
  <option val="25">25</option>
  <option val="50">50</option>
  <option val="100">100</option>
  <option val="250">250</option>
</select> <br />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Using Many Variables from JS Document Pathname

If you wanted to use many parameters, just extend the same logic. For instance, imagine: /GCValue=50/Page=765/Index=42/...

var url = "https://mywebsite.com/GCValue=50/Page=765/Index=42/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /([A-Za-z0-9] )=([0-9] )/g;
var match;
while ((match = regex.exec(url)) != null) {
    document.getElementById(match[1]).value = match[2];
}
<select id="GCValue">
  <option val="10">10</option>
  <option val="25">25</option>
  <option val="50">50</option>
  <option val="100">100</option>
  <option val="250">250</option>
</select> <br />

<input id="Page" type="text"><br>
<input id="Index" type="text">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Here is a simple solution for you:

const selectList = document.getElementById('GCValue');

selectList.selectedIndex = '2';

Even shorter:

document.getElementById('GCValue').selectedIndex = '2';

'2' is the index number of value="50" in your dropdown. If you add more options before it, index number changes.

  • Related