多个html select和jquery ajax [英] Multiple html select and jquery ajax

查看:89
本文介绍了多个html select和jquery ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建多个<选择>并使用ajax和jquery.

I wanna create a multiple < select > with ajax and jquery.

首先选择(c1)正常工作.当我单击它时,将返回另一个select(c2).但是,当我单击第二个select(c2)时,我可以得到第三个select(c3).

First select(c1) is working properly. When I click on it returns another select(c2). But when I clicked on second select(c2) I can get third select(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>
<?

对不起,我的英语,谢谢您的帮助

Sorry for my English and thanks for any help

推荐答案

这应该可以解决问题:

$(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处理程序绑定到...您需要在元素存在后执行此操作就像我上面一样.

Currently, when $("select[name=c2]") runs, the element isn't there yet...so there's nothing to bind a change handler to...you need to do this once the element is there, like I have above.

这篇关于多个html select和jquery ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆