Главная > Javascript, PHP > Зависимые select

Зависимые select

Javascript:

$(document).ready(function(){
	var select_brand=$('select[name=brand]');
	var select_collection=$('select[name=collection]');
	select_brand.on('change',function(){
		$.ajax({
			url:"/?ajax_action=get_collections&brand="+select_brand.val(),
			dataType:"json",
			success:function(data){
				select_collection.find('option').not(':first').remove();
				$.each(data,function(index,item){
					select_collection.append('<option value="'+item.id+'">'+item.name+'</option>');
				});
				select_collection.trigger("chosen:updated");
			}
		});
	});
});

HTML:

<select name="brand" class="chosen">
	<option value="0">Выбрать</option>
	<?if(count($brands)>0){?>
		<?foreach($brands as $item){?>
			<option value="<?=$item['id']?>"<?if($item['id']==$change_catalog["brand"]){?> selected="selected"<?}?>><?=$item['name']?></option>
		<?}?>
	<?}?>
</select>
<select name="collection" class="chosen">
	<option value="0">Выбрать</option>
	<?if(count($collections)>0){?>
		<?foreach($collections as $item){?>
			<option value="<?=$item['id']?>"<?if($item['id']==$change_catalog["collection"]){?> selected="selected"<?}?>><?=$item['name']?></option>
		<?}?>
	<?}?>
</select>

PHP:

if($_GET['ajax_action']=='get_collections'&&$_GET['brand']>0){
	header("Content-Type: application/json");
	$result=get_from_base('`id`,`name`','collections',"`parent`='".$_GET['brand']."'",'pos');
	echo json_encode($result);
	exit();
}
$brands=get_from_base('`id`,`name`','brands',"1",'`parent`,`pos`');
if($_GET["change_id"]){
	$change_catalog=get_by_id($_GET["change_id"],'catalog');
	if($change_catalog['brand']){
		$collections=get_from_base('`id`,`name`','collections',"`parent`='".$change_catalog['brand']."'",'pos');
	}
}
Categories: Javascript, PHP Tags: ,
  1. Пока что нет комментариев.
Похожие публикации