2010-11-10 9 views
0

Je veux créer un multiple < select> avec ajax et jquery.Multiple html select et jquery ajax

La première sélection (c1) fonctionne correctement. Quand je clique dessus, cela renvoie une autre sélection (c2). Mais quand j'ai cliqué sur la deuxième sélection (c2) je peux obtenir le troisième choix (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> 
<? 

Désolé pour mon anglais et merci pour toute l'aide

Répondre

0

Cela devrait faire l'affaire:

$(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); 
      } 
      }); 
     }); 
     } 
    }); 
    }); 
}); 

Actuellement, lorsque $("select[name=c2]") fonctionne, l'élément est pas encore là ... donc il n'y a rien à lier un gestionnaire change à ... vous devez faire une fois l'élément est là, comme je avoir ci-dessus.

+0

Je ne connais pas PHP mais il me semble que ces boucles de son (ou son) pour générer les éléments "" après chaque '