【问题标题】:Jquery: Get value of more than one <select> drop-downJquery:获取多个<select>下拉列表的值
【发布时间】:2012-12-25 02:43:54
【问题描述】:

我正在从数据库表中获取用户记录

<?php $row=1; ?>
<select id="status<?php echo $row; ?>" name="status<?php echo $row; ?>">
    <option value="0">Active</option>
    <option value="1">Block</option>
</select>
<?php $row++; ?>

----------------------------------------
  Name                    Status
----------------------------------------
  Abc                     Active
  Def                     Block
  Ghi                     Active
  Jkl                     Block
----------------------------------------

其中 status 是下拉列表,每个用户有两个状态,如果我想更改任何用户的状态,那么我从该下拉列表中选择一个选项,同时状态必须在 db-table 中更新。 为此我编写了代码:

for(var r=1; r<=4; r++){
    $("status").each(function() {
        var sld = $("#status").val();
        alert(sld);
        $.ajax({
            type: "POST",
            url: "response.php",
            data: "sld="+sld,
            success: function(msg){
                alert(msg); // this is the response
            }
        });
    });
}

但 for 循环不会为每个下拉菜单创建脚本......

【问题讨论】:

  • 好吧,看来你搞错了。首先,第 2 行中的“状态”看起来需要是“.status”,并且每个下拉菜单都需要状态类。状态 ID 不起作用,因为您只能拥有一个
  • 您的 PHP 代码与问题无关。您应该包含 PHP 发出的 HTML,因为这是浏览器和 JavaScript/jQuery 正在查看的内容。 (提示:查看源代码或检查元素)

标签: php jquery


【解决方案1】:

您需要删除该 for 循环,并使用此代码。 我的事件现在是“更改”,它将提交两个变量,“id”和“sld”。然后更新 php 脚本以检查 $_POST['id'] 和 $_POST['sld'],然后将它们更新到数据库中。

在每个下拉菜单中添加 class="status"。

$(".status").change(function() {
        var sld = $(this).val();
        alert(sld);
        $.ajax({
            type: "POST",
            url: "response.php",
            data: { "sld": sld, "id":$(this).attr('id').replace('status','') },
            success: function(msg){
                alert(msg); // this is the response
            }
        });
    });

【讨论】:

    【解决方案2】:

    $('status') 将选择节点名称为status 的元素。你有吗?还是你的意思是$('.status')

    【讨论】:

      【解决方案3】:

      我认为您拥有多个具有相同 ID 的元素,这将是无效的 HTML。

      为你的选择框设置一个类,然后你就可以使用这样的东西了。

      $("select.status").each(function() {
          var sld = this.value;
          alert(sld);
          $.ajax({
              type: "POST",
              url: "response.php",
              data: "sld="+sld,
              success: function(msg){
                  alert(msg); // this is the response
              }
          });
      });
      

      我也没有发现示例中使用了 for 循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 2023-03-27
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        相关资源
        最近更新 更多