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>
3
  • You mean you are not able to see the option with value equal to 3 selected? Commented Feb 16, 2015 at 8:52
  • Yes, it is always value 1 that is selected! Commented Feb 16, 2015 at 8:55
  • That regex only works if you have more than 1 parameters, like http://example.com/Betreff=3&Inhalt=something Commented Feb 16, 2015 at 8:58

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

0

Try this:

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

1 Comment

thanks you for your effort! But Rory McCrossan answer was exactly what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.