根据另一个选择更新一个选择

时间:2012-08-21 12:26:23

标签: php ajax jquery symfony

  

可能重复:
  How to load second dropdown list from database after first dropdown list is changed

嘿,我有一个表格,里面有两个选择下拉列表。

第一个选项填充了用户的投资组合,第二个选项需要填充投资组合。我获得了登录用户的所有投资组合,并使用这些投资组合填充第一个选择我想在第一个选择的基础上填充第二个选择组,例如,如果用户选择portfolio_1,portfolio_1中的所有组应该在第二个选择框中加载。

投资组合的第一个选择是:

<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
    <option selected="selected" value="default">Select Portfolio</option>
    {% for portfolio in portfolios %}
        <option value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
    {% endfor %}
</select> 

我理解的是我需要在第一个选择的更改中调用ajax函数,因为ajax我需要发送选定的投资组合ID并查找具有该id的所有组,然后返回所有这些组并仅更新第二个选择这些组的框,

我不知道如何使用我将获得的组填充第二个选择

任何想法?

由于

2 个答案:

答案 0 :(得分:0)

<select id="portfolios" name="portfolio" style="width: 200px; height:25px;" onchange="getgropus(this.value)">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
    <option value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select>
<select id="secondselectBox" name="secondselectBox"  ></select>

call the ajax function on the onchange event of your 1st selectbox
// here is JS code

<script type="text/javascript">
function getgropus(id){
        $.ajax({
            type: 'post',
            url: "your php file path to get groups ",
            data: "&id="+id,
            complete: function(data) {
                $('#secondselectBox').html(data.responseText)
            }
        });
}

</script>

on your php file make options for selectbox of group portfolio and adjust according to your requirnments

<option value="default">Portfolio groups</option>
 .......

答案 1 :(得分:0)

我会以JSON格式返回它们,然后将它们注入DOM:

$('#portfolios').on('change', function(){
   $.getJSON('url/for/groups', function(pgroups) {
       var html = '';

       $.each(pgroups, function(value, name) {
           html += '<option value="'+value+'">'+name+'</option>';
       });

       $('#portfolio-groups').html(html);
   });
});
相关问题