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);
        });
      });
    )};
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?