-1

我遇到了一个问题,我使用 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
            });

        }); 
4

1 回答 1

1

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

将您的脚本更改为

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',
    .....
  });
}); 

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

于 2015-02-13T02:53:10.230 回答