-1

AJAX(JSON) を使用してデータリストを作成しているときに問題が発生しました。データリストからオプションを選択し、[FIND TIMESHEETS] ボタンをクリックして、選択したプロジェクト 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>要素を 1 つだけ含む要素を要素に追加します。Aは要素のみを必要とします。ボタンのクリック ハンドラで、 を読み込もうとしています。(無効な html)を持つ複数の要素がありますが、いずれにせよ、データリストからオプションを選択しても、.<option>data-id<datalist><datalist><option>$('#selectList option:selected')id="selectList"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 に答える