【问题标题】:Get the selected option from datalist in Javascript从 Javascript 中的 datalist 中获取选定的选项
【发布时间】:2016-02-17 18:40:04
【问题描述】:

现在我知道有与我类似的问题。但在这种情况下,如果可能的话,请在不使用 PHP 的情况下解释......只是 JavaScript!

在 HTML 中,我有以下代码:

<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>

由于无法更改 HTML,因此我使用 JavaScript 添加了选项:

 var list = document.getElementById("cities");
 var option = document.createElement("option");
 option.text = "New Delhi";
 list.appendChild(option);

想象一下数据列表中有更多选项。 因此,在 javaScript 中,我如何选择用户选择的选项。因为 .selected 不适用于 dataList。

也与您发布的问题不同。我不能使用除 javascript 之外的任何其他语言。我也不能向选项标签添加更多属性。这就对了。我从服务器获取城市名称的列表。我正在通过 for 循环将它们一一放入数据列表中。

【问题讨论】:

标签: javascript html html-datalist


【解决方案1】:

好的。对代码做了一些乱七八糟的事情。

var selectedCity = document.getElementById("citiesinput");

var selectedCity 现在保存在数据列表中选择的选项。 我对自己很失望。但以防万一其他人搞砸了。

在数据列表中,您不需要 .selected 命令。

【讨论】:

    【解决方案2】:

    你必须将它发布到 php。

    试试这个:http://codesheet.org/codesheet/wOHDXFju

    onmousedown="javascript:postContent('1','New Delhi');"
    

    .js

    function postContent(pid, pc) {
      $("#myDiv").html('L  O  A  D  I  N  G ...').show();
      var url = "/post.php";
      $.post(url, {id: pid, city: pc} ,function(data) {  //contentVar is the variable in post.php
           $("#myDiv").html(data).show();
        });
    }
    

    这是将您的数据发布到在这种情况下 post.php 到 div#myDiv

    【讨论】:

    • 非常感谢老兄。
    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多