2015-11-04 67 views
0

我新的jQuery和我想知道,如果他能够JSON数组。 我有一个PHP控制器发送JSON编码数组到一个视图, 这是JSON数组:操纵的选择变化

{"id":"1","color":"blue","description":"This is the color blue"}, 
{"id":"8","color":"green","description":"This is the color green"}, 
{"id":"14","color":"red","description":"This is the color red"} 

现在在视图上我有以下几点:

<select id="selector"> 
<option value="">Select one</option> 
<option value="1">blue</option> 
<option value="8">green</option> 
<option value="14">red</option> 
</select> 

<div id="description"> 

</div> 

我想要什么做的是首先从JSON数组填充选择列表,然后,如果我选择了绿色的描述应该出现在DIV,如果我改变我的选择合适的描述应该出现在格的下拉列表中绿色。 我选择该选项将不再出现在选择列表上一样,如果我选择绿色,只有红色和蓝色应该出现在可用的选项,如果我选择另一种颜色,让说,蓝色然后红色和绿色应该可用于其他选择。

我目前做它运行一个新的查询平变化的选择,但我想这样做没有另一个查询和页面刷新,我想这是可能的,因为我已经发送JSON阵列到浏览器。

希望我是对我的问题清楚,感谢您的帮助!

+2

这不是有效的JSON。 – TheCarver

+0

你将不得不发布你的Javascript/jQuery代码。我猜想畸形的JSON来自AJAX,但我们需要看看你是如何得到这一点,然后我们可以帮助你更好。 – TheCarver

回答

0
var data = [{"id":"1","color":"blue","description":"This is the color blue"}, 
{"id":"8","color":"green","description":"This is the color green"}, 
{"id":"14","color":"red","description":"This is the color red"}]; 
var selector = $('#selector'); 

data.forEach(function(obj){ 
    // create option 
    var option = $('<option>'); 
    // set its value 
    option.val(obj.id); 
    // set its text 
    option.text(obj.text); 
    // append it to select element 
    selector.append(option); 
}  
selector.change(function(){ 
    var value = this.value; 
    // show all options 
    selector.find('option').show(); 
    // hide the selected 
    $(value).hide(); 
    // find the selected object 
    var selected = data.filter(function(obj){ 
     return obj.id == value; 
    }); 
    // if returns exactly one show its description 
    if (selected.length == 1) 
     $('#description').text(selected[0].description); 
}); 
+0

感谢的Almis,这几乎是所有我需要的,现在还有一两件事,我如何删除所选的选项,就像如果我选择绿色,只有蓝色和红色应该出现,但如果当时我选择蓝,绿应该再次同时出现红色 –

+0

@ALDI检查编辑 – Almis

+0

非常感谢您的帮助! –

0

首先,你必须Json是这样的:

[{"id":"1","color":"blue","description":"This is the color blue"}, 
{"id":"8","color":"green","description":"This is the color green"}, 
{"id":"14","color":"red","description":"This is the color red"}] 

这是一些代码,我已经尝试我认为这将帮助你:

$(document).ready(function(e){ 
    $("#selector").on('change',function(){ 
     var dataL= $("#selector option:selected").val(); 
     $.post("Page_json.php",{myVal:dataL},function(data,message,xhr){ 
          if(message==='success'){ 
           $.each(data, function(k,v){ 
            if(v.id == dataL){ 
             $("#description").text(v.description); 
             return false; 
            } 
           }); 
          } 
         },'json'); 


    }); 
});