简体   繁体   English

通过JavaScript填充下拉框更改所选项目

[英]Populating Drop Down Boxes Via Javascript Change Selected Item

I populate a drop down box from an array that uses Javascript on the page load. 我从在页面加载中使用Javascript的数组填充一个下拉框。 But I am pulling data out of a database how would I change which one was selected? 但是我要从数据库中提取数据,我将如何更改选择的数据库? I would prefer not to have to use PHP to create the drop down boxes, as I have other non php things that use the javascript as well. 我希望不必使用PHP创建下拉框,因为我还有其他使用javascript的非PHP东西。 What Can I do to get my Drop DownList populated from PHP? 如何使我的Drop DownList从PHP填充?

You can see that it just calls the SelectdeptDropdown function. 您可以看到它只是调用SelectdeptDropdown函数。

<label for="collegedropdown">Collge</label>
<select name="collegedropdown" id="collegedropdown" onChange="SelectDeptDropdown();">
  <option selected="selected">Choose a college</option>
</select>
<br /> 
<label for="deptdropdown">Department</label>
<select name="deptdropdown" id="deptdropdown">
  <option selected="selected">Choose a department</option>
</select>

Javascript Code: JavaScript代码:

removeAllOptions(document.profilecreate.deptdropdown);
addOption(document.profilecreate.deptdropdown, "", "Choose One", "");

if(document.profilecreate.collegedropdown.value == 'MY CHOICE #1'){
//all options here
}
//repeat for other cases here

NOTE: removeAllOptions calls another function that simply clears the dropdown list. 注意:removeAllOptions调用另一个仅清除下拉列表的函数。 addOption calls a function that creates the option element. addOption调用创建选项元素的函数。

basically you need to use an XHR Request . 基本上,您需要使用XHR Request The XHR request will hit another end point of your php server which will return data for you to populate the dropwdown field and then you can use some smart javascript to insert into the dom. XHR请求将到达您的php服务器的另一个端点,该端点将返回数据供您填充dropwdown字段,然后您可以使用一些智能javascript插入dom。

Tne end point should ideally return a json data which will only be the dropdown values and you generate the markup on the client side this is ont compulsory but recommended.. read more abt XHR and json here . 理想情况下,该端点应返回一个json数据,该数据将仅是下拉值,并且您在客户端生成标记,这是强制性的,但建议这样做。 在此处阅读更多内容abt XHR和json。

Finally I would suggest you to use a library like jquery that gives you simple api for XHR requests and DOM manipulation using which you can get your job done quickly. 最后,我建议您使用类似jquery的库,该库为XHR请求和DOM操作提供简单的api,从而可以快速完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM