Stephen.J7 Stephen.J7 - 6 months ago 16
Javascript Question

Default dropdown value on load from hyperlink with java

I did some searching and couldn't find an exact answer on how to do this (especially for a noob like me) I would like to set a dropdown value on page load based off a variable in the href hyperlink.

Example with default dropdown: mywebsite.com&value=4

This would apply the dropdown item associated with value 4 when the page loaded.Below is the HTML for the drop down selector but I currently have no java for it. Is it possible for it to pull a variable from hyperlink? Thanks for any help.

<select id="subject" name="subjectlist" size="1" onchange="SetActivity();">
<option value="1^Non-Urgent Medical Question">Non-Urgent Medical Question</option>
<option value="2^Medication Question">Medication Question</option>
<option value="3^Test Results Question">Test Results Question</option>
<option value="4^Visit Follow-Up Question">Visit Follow-Up Question</option>
<option value="5^Medical Record Question / Correction">Medical Record Question / Correction</option>
</select>

Answer

If you have control of the URL, you can change the format and use a hash.

So for value=4, the URL is: http://example.com/#value=4

if (window.location.hash.length > 0){
    var matches = window.location.hash.match(/value=([0-9]+)/i);
    if (matches.length > 1){
        var value = matches[1];
        $("#subject option[value^='"+value+"^']").attr('selected', true);
    }
}

Alternatively, you could filter the options based on value. Safer than the above code:

if (window.location.hash.length > 0){
    var matches = window.location.hash.match(/value=([0-9]+)/i);
    if (matches.length > 1){
        var value = matches[1];
        $("#subject option").filter(function(){
            return $(this).val().indexOf(value+'^') === 0;
        }).attr('selected', true);
    }
}

If you don't want to use a hash (#), you could use window.location.href instead. You'd just modify the RegEx a bit (so it's guaranteed to be at the end of the URL).

Comments