简体   繁体   English

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

[英]Can't get value of <select> element in jQuery

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. 我想在jQuery中创建一个类似于Google表格的网络应用,但是当我尝试使用$(select).val()获取<select>值时,我会得到`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. 我试图将代码放入$(button).click() ,然后它起作用了,所以我认为问题是Javascript在HTML之前执行,但我不确定。

$(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() . 我只想获取$("#tables_SCT").val()

You will need to put the var name = $("#tables_SCT").val(); 您将需要输入var name = $("#tables_SCT").val(); line inside the first AJAX callback. 第一个AJAX回调内的代码行。 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. 就目前而言,您的代码正在尝试读取DOM中尚不存在的内容,因为填充选项元素的请求是异步的。

You will also need to make the second AJAX call from this point too, for the same reason. 由于相同的原因,您也将需要从此开始第二个AJAX调用。 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);
    });
  });
)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM