简体   繁体   中英

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.

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() .

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);
    });
  });
)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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