dqrnsg6439 2019-06-21 09:28 采纳率: 100%
浏览 190
已采纳

无法在jQuery中获得<select>元素的值

I want to create a web app like google sheets in jQuery, but when I try to get a <select> value with $(select).val() I get `null.

I tried to put the code into $(button).click() and then it worked so I think the problem is that Javascript is executed before HTML, but I am not sure.

$(function() {
  $.post("getTablesName.php", function(data) {
    $("#tables_SCT").html(data);
  });

  var name = $("#tables_SCT").val();
  $.get("getTable.php", { name: name }, function(data) {
    $("#columns").html(data);
  });
)};

I just want to get the $("#tables_SCT").val().

  • 写回答

1条回答

  • duaijiao0648 2019-06-21 09:38
    关注

    You will need to put the var name = $("#tables_SCT").val(); line inside the first AJAX callback. As it stands your code is trying to read content which doesn't yet exist in the DOM as the request which fills the option elements is asynchronous.

    You will also need to make the second AJAX call from this point too, for the same reason. Try this:

    $(function() {
      $.post("getTablesName.php", function(data) {
        $("#tables_SCT").html(data);
    
        var name = $("#tables_SCT").val();
        $.get("getTable.php", { name: name }, function(data) {
          $("#columns").html(data);
        });
      });
    )};
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码