1

How can I have my dropdown selected with an url parameter? I found this: Dropdown selected based on URL parameter - PHP or jQuery?

But it does not work for me. What am I doing wrong? My url would be:

kontakt.php?Betreff=3

script:

var val = location.href.match(/[?&]Betreff=(.*?)[$&]/)[1];   // get params from URL
$('#Betreff').val(val);   //  assign URL param to select field

and:

<select class="mailstyle" name="Betreff" id="Betreff">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
</select>
Community
  • 1
  • 1
user2961970
  • 367
  • 1
  • 5
  • 9

3 Answers3

3

Your regex is incorrect. You can use this function (from this question) to get the parameter value:

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

You can then use that to set the value:

var val = getURLParameter('Betreff');
$('#Betreff').val(val);   //  assign URL param to select field
Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Try this:

var val = location.href.match(/[?&]Betreff=(.*?)(?:$|&)/)[1];   // get params from URL
$('#Betreff').val(val);   //  assign URL param to select field
0

Try this:

$('#Betreff option').each(function(){
    if($(this).val()==val){
        $(this).attr("selected","selected");
        break; 
    }
});