从Javascript中的datalist获取所选选项

时间:2016-02-17 18:40:05

标签: javascript html html-datalist

现在我知道有类似我的问题。但在这种情况下,请尽可能不使用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);

想象一下,datalist中有更多选项。 所以在javaScript中如何选择哪个选项是用户选择的选项。因为.selected不适用于dataList。

与您发布的问题不同。我不能使用任何其他语言而不是JavaScript。此外,我可以不为选项标签添加其他属性。这就对了。我从服务器获取城市名称的列表。我通过for循环将它们逐个放入datalist中。

2 个答案:

答案 0 :(得分:0)

你将它发布到php。

试试这个:MiniZinc documentation

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

答案 1 :(得分:0)

好。做了一些搞乱的代码。

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

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

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

相关问题