2010-11-10 74 views
0

我想創建一個多選< select> with ajax和jquery。多選擇html和jquery ajax

首先選擇(c1)工作正常。當我點擊它時會返回另一個選擇(c2)。但是當我點擊第二選擇(c2)時,我可以得到第三選擇(c3)。

HTML:

<table><tr><td id="cat1div"> 
<select name="c1"> 
<option value="">---</option> 
<option value="1">Auto</select> 
<option value="2">Moto</select> 
</td> 
<td id="cat2div"></td> 
<td id="cat3div"></td> 
</tr></table> 

的jQuery:

$(document).ready(function() { 
$("select[name=c1]").change(function() { 
var id = $("select[name=c1] option:selected").val(); 

$.ajax({ 
      url: "category.php?cat=2&id=" + id, 
      cache: false, 
      success: function (html) { 
       $('#cat2div').html(html); 
      } 
     }); 

}); 



$("select[name=c2]").change(function() { 
alert('asad'); 
var id = $("select[name=c2] option:selected").val(); 

$.ajax({ 
      url: "category.php?cat=3&id=" + id, 
      cache: false, 
      success: function (html) { 
       $('#cat3div select').html(html); 
      } 
     }); 

}); 

}); 

PHP:

<?if($_GET['cat']==2){?> 
<select name="c2"> 
<option value="">---</option> 
<?foreach($cat2[$_GET['id']] as $ca => $key){ 
?><option value="<?=$ca;?>"><?=$key;?><?}?> 
</select> 
<?}elseif($_GET['cat']==3){?> 
<select name="c3"> 
<option value="">---</option> 
<?foreach($cat3[$_GET['id']] as $ca => $key){ 
?><option value="<?=$ca;?>"><?=$key;?><?}?> 
</select> 
<? 

對不起,我的英語水平,並感謝所有幫助

回答

0

這應該做的伎倆:

$(document).ready(function() { 
    $("select[name=c1]").change(function() { 
    $.ajax({ 
     url: "category.php?cat=2&id=" + $(this).val(), 
     cache: false, 
     success: function (html) { 
     $('#cat2div').html(html).find("select[name=c2]").change(function() { 
      $.ajax({ 
      url: "category.php?cat=3&id=" + $(this).val(), 
      cache: false, 
      success: function (html) { 
       $('#cat3div select').html(html); 
      } 
      }); 
     }); 
     } 
    }); 
    }); 
}); 

目前,當$("select[name=c2]")運行,該元素是不存在尚未...所以沒有什麼綁定一個change處理程序...你需要做一次的元素那裏,像我有以上。

+0

我不知道PHP,但它看起來好像他的(或她的)生成''...... – Pointy 2010-11-10 19:13:32