[英]Pass a value from a URL into a Drop Down List using Javascript
I have a url as follows 我有一个网址如下
http://*****************?ContentId=1335&clientName=Sam&clientPhone=123&clientEmail=an@gmail.com&clientCountry=United%20Kingdom.
clientCountry is a name of a drop down list in my form and I want to pass the value (United Kingdom) into that drop down list using Javascript. clientCountry是表单中下拉列表的名称,我想使用Javascript将值(英国)传递到该下拉列表中。
I have been able to do this so far 到目前为止,我已经能够做到这一点
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var first = getUrlVars()["clientName"];
var second = getUrlVars()["clientPhone"];
var third = getUrlVars()["clientEmail"];
var fourth = getUrlVars()["clientCountry"];
Now I do not know how to pass the variable fourth into the drop down list. 现在,我不知道如何将第四变量传递到下拉列表中。 Can anyone assist as I am a total novice with javascript?
任何人都可以帮助我,因为我是javascript的新手?
If you have already populated the dropdown list, this should work for preselecting the value from the URL: 如果您已经填充了下拉列表,那么这应该可以从URL中预选择值:
var dropDowns = document.getElementsByTagName('select'), opts, i;
for(i = 0, l=dropDowns.length;i<l;++i){
if(dropDowns[i].name === 'countryList'){
opts = dropDowns[i].getElementsByTagName('option');
for(i = 0, l = opts.length;i<l;++i){
if(opts[i].value === fourth){
opts[i].selected = true;
break;
}
}
break;
}
}
Make sure this runs after you print the markup for the select by binding to the document ready event, or include it somewhere in the page after you print the markup for the dropdown list. 确保通过绑定到文档就绪事件来打印选择的标记后运行该标记,或者在打印下拉列表的标记后将其包括在页面中的某处。 It uses the fourth variable from the code you included, so that should have run when you run this.
它使用您包含的代码中的第四个变量,因此在运行此变量时应已运行该变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.