【问题标题】:Get the Values of Option attribute in datalist in HTML5 that is dynamically generated from AJAX Calls获取 HTML5 中 datalist 中由 AJAX 调用动态生成的 Option 属性的值
【发布时间】:2015-02-13 10:53:10
【问题描述】:

我在使用 AJAX(JSON) 填充数据列表时遇到了问题。我希望能够从数据列表中选择选项并单击“查找时间表”按钮并根据该选定的项目 ID 进行更多的 ajax 调用。我的代码如下所示。

我的 HTML

 <div id="datalist" class="hide">
        <label id="labelPl" for="projectList">Select your project from the list: </label>
        <input type="text" id="ProjName" list="projectList" placeholder=" Project Search by Client's Name : e.g. google, microsoft,caresource etc.">
        <datalist id="projectList"></datalist>
        <button id="find-ts" class="btn btn-primary">Find Timesheets</button>
    </div>

成功填充项目列表的我的 AJAX

 $('#ProjName').on('input', function (e) {
                var val = $(this).val();
            if (val === "") return;
            var query = $('#ProjName').val();
            var uId=@Model.Id;
            $.getJSON("/Search/Projects", { userId: uId, query: query }, function (data, xhr) {
                var dataList = $('#projectList');
                dataList.empty();
                $.each(data, function (i, item) {
                    var sdate = new Date(parseInt(item.StartDate.substr(6)));
                    formatStartDate = (sdate.getMonth() + 1) + '/' + sdate.getDate() + '/' + sdate.getFullYear();
                    var fromatEndDate;
                    if (item.EndDate == null) {
                        fromatEndDate = "Present";
                    }
                    else {

                        fromatEndDate = item.EndDate;
                    }
                    var opt = $("<option class='selected-project' style='min-height:4em'></option>").attr({
                        "value":item.Name + " (from " + formatStartDate + " to " + fromatEndDate + ")",
                        "data-id":item.Id
                    });
                    var select=$('<select id="selectList"></select>')
                    dataList.append(select.append(opt));
                });
            });

按钮的我的 ONCLICK 事件监听器

  $('#find-ts').click(function () {
            //get the id of the selected from datalist
            var val = $('#ProjName').val()
            var selectedId=$('#selectList option:selected').attr('data-id');
            var projId = selectedId ? selectedId : 0; //set it to zero if not found
            //
            console.log("the projectId is ", projId); //This is where I need my projectId so that I can pass in into the controller action method.
            $.ajax({
                url: 'url?projId=' + projId,
                type: 'GET',
                beforeSend: function before() {
                    loadingBar(true);
                },
                complete: function complete() {
                    var myVar = setInterval(function () { loadingBar(false); }, 5000);
                },
                success: function (result) {}
                //doing some calculation here
            });

        }); 

【问题讨论】:

  • 有什么问题?
  • 问题是当我点击 FIND TIMESHEETS 按钮时,我得到的是 projId=0 而不是我从 JSON 返回的项目的实际 projId
  • 你的代码没有意义。你有一个datalist 标签。 datalist 的子元素是 &lt;option&gt; 元素。您似乎正在尝试为集合中的每个项目添加一个包含一个 &lt;option&gt;&lt;select&gt;。在任何情况下,由于无效的 html,您生成的 $('#selectList option:selected').attr('data-id'); 只会返回第一个 &lt;select&gt;data-id 值,即使它确实有效。

标签: jquery ajax asp.net-mvc html html-datalist


【解决方案1】:

您处理文本框的输入事件以向您的&lt;datalist&gt; 元素添加一个&lt;select&gt; 元素,该元素仅包含一个具有data-id 属性的&lt;option&gt; 元素。 &lt;datalist&gt; 只需要 &lt;option&gt; 元素。在按钮单击处理程序中,您尝试读取 $('#selectList option:selected')。您有多个带有id="selectList"(无效html)的元素,但无论如何,从数据列表中选择一个选项不会将selected 属性添加到&lt;option&gt;

将脚本更改为

var uId = '@Model.Id';
var url = '@Url.Action("Projects", "Search")'; // dont hard code your urls!
var dataList = $('#projectList'); // cache it

$('#ProjName').on('input', function (e) {
  var query = $(this).val();
  if (!query) {
    return;
  }
  $.getJSON(url, { userId: uId, query: query }, function (data) {
    dataList.empty();
    $.each(data, function (i, item) {
      var sdate = // get rid of this and do the formatting on the server and return a string!
      dataList.append($('<option></option>').val(sdate).data('id', data.Id));
      // it should be: dataList.append($('<option></option>').val(item.Text).data('id', item.Id));
    });
  });
});

$('#find-ts').click(function () {
  var text = $('#ProjName').val();
  var option = dataList.children('option').filter(function () {
    return $(this).val() == text;
  })
  var selectedId = option.data('id'); // this will contain the Id
  $.ajax({
    url: '@Url.Action("YourAction", "YourController")',
    data { projId: selectedId }, // add the parameters this way
    type: 'GET',
    .....
  });
}); 

旁注:向选项元素添加类名和内联样式是没有意义的。它们由浏览器/操作系统呈现,您几乎无法控制它们的呈现方式。

【讨论】:

  • 效果很好!谢谢斯蒂芬!
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2016-01-05
  • 2014-12-20
  • 2014-10-18
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多