[英]PHP: Two <select>, first one allready fill, the second one I want to fill with values
I am have this issue: 我有这个问题:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do. 现在,我想做什么。 The second select list is empty initially.
第二个选择列表最初是空的。 I want to fill it with values depending of what is chose in first select list.
我想根据第一选择列表中选择的值来填充它。
How can I do that? 我怎样才能做到这一点? To fill the second select list only if something is selected in first select list.
仅当在第一选择列表中选择了某些内容时才填充第二选择列表。
MrCode has a nice example for you. MrCode为您提供了一个很好的例子。
Using Ajax To Populate A Select Box 使用Ajax填充选择框
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with 您的select.php应该使用json_encode()数据来填充您的选择
The best way to handle this would be to populate the list after you made a change on the first list. 最好的方法是在第一个列表上进行更改后填充列表。 For example.
例如。
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. 我不得不做几个假设。 for example your some.php will take a value parameter.
例如,您的some.php将采用值参数。 The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}].
返回的是json数组[{id:1,name:“ option 1”},{id:2,name:“ option 2”}]。 Please keep this in mind.
请记住这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.