Preselect dropdown

Hello guys,

I’ve been desperately trying to figure out how to pre-select a dropdown from url parameter. I’m currently already doing this for input fields, but I am struggling to do the same with a drop down. Please can anyone help.

url:


http://localhost/graburl.html?var_email=jkahn@silverpop.com&opition_select=foo

pre-populate


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function gup( name ){
name = name.replace(/[\\[]/,"\\\\\\[").replace(/[\\]]/,"\\\\\\]");
var regexS = "[\\\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var var_email = gup( 'var_email' );
var opition_select = gup( 'opition_select' );
</script>
</head>
<body >
<!--
http://localhost/graburl.html?var_email=jkahn@silverpop.com&opition_select=foo-->

<form method="POST" action="something.cgi" id="frmPreselect" name="frmPreselect">

<script type="text/javascript">
document.write('<input ');
document.write(' type="text" ');
document.write(' name="var_email" ');
document.write(' value="' + var_email + '">');
</script><br />

<select name="ddl_example4" id="ddl_example4">
<option value="test">test</option>
<option value="foo">foo</option>

</select>


</form>

</body>
</html> 


Come-on guys…there must be someone out here who can help!

Here’s something that’s been rapidly put together


function selectOption(select, name) {
    var options = select.options,
        i;
    for (i = 0; i < options.length; i += 1) {
        if (options[i].value = name) {
            options[i].setAttribute('selected', 'selected');
        } else {
            options[i].removeAttribute('selected');
        }
    }
}

// the variable called "name" is the one that is retrieved from the querystring
var form = document.getElementById('frmPreselect'),
    select = form.elements.ddl_example4;
selectOption(select, name);

pmw57 thanks for that. I ended-up doing a series of if statements which was not efficient. I’ll give your code a try.