简体   繁体   English

在下拉菜单中维护选定的值

[英]Maintain Selected Values in Dropdown Menu

I have a cascading dropdown menu populated by an AJAX call which works as intended. 我有一个按预期工作的AJAX调用填充的级联下拉菜单。 However, when I submit the form and refresh the page, the selected values reset. 但是,当我提交表单并刷新页面时,所选值将重置。 I'd like to be able to maintain the selected values within their drop-down boxes upon submitting the form and refreshing the page. 提交表单并刷新页面后,我希望能够在其下拉框中保留选定的值。

I've found several solutions on Stack Overflow already, but can't seem to find one that shows how to maintain the selected values from a form who's options are dynamically populated. 我已经在Stack Overflow上找到了几种解决方案,但是似乎找不到一种解决方案来显示如何维护从动态填充选项的表单中选择的值。

My HTML and JS are below. 我的HTML和JS在下面。

<form method="get" class='d-print-none' id='gameForm' team-ids-url={% url 'ajax_load_teamids' %} game-ids-url={% url 'ajax_load_gameids' %} novalidate>
<div class="input-group">
<select class="custom-select" id="inputTeamId" name="inputteamid"></select>
<select class="custom-select" id="inputGameId" name="inputgameid"></select>
<div class="input-group-append">
  <button class="btn btn-outline-secondary" type="submit" value="submit" onclick="loading();">Run</button>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
var url = $("#gameForm").attr("team-ids-url");
$.ajax({
  url: url,
  success: function(data) {
    $("#inputTeamId").html(data);
  }
});
});
$("#inputTeamId").change(function() {
var url = $("#gameForm").attr("game-ids-url");
var selected_teamid = $(this).val();
localStorage.setItem("SelectedTeamId", selected_teamid);
$.ajax({
  url: url,
  data: {
    'selected_teamid':selected_teamid
  },
  success: function (data) {
    $("#inputGameId").html(data);
  }
})
})
</script>

Consider the following code: https://jsfiddle.net/Twisty/5p2yg034/ 考虑以下代码: https : //jsfiddle.net/Twisty/5p2yg034/

HTML HTML

<form method="get" class="d-print-none" id="gameForm" data-team-url="./teams" gdata-game-url="./games">
  <div class="input-group">
    <select class="custom-select" id="inputTeamId" name="inputteamid">
      <option></option>
      <option value="t1">Team 1</option>
      <option value="t2">Team 2</option>
      <option value="t3">Team 3</option>
    </select>
    <select class="custom-select" id="inputGameId" name="inputgameid">
      <option></option>
      <option value="g1">Game 1</option>
      <option value="g2">Game 2</option>
      <option value="g3">Game 3</option>
    </select>
    <div class="input-group-append">
      <button class="btn btn-outline-secondary" type="submit" value="submit" onclick="loading();">Run</button>
    </div>
  </div>
</form>

One thing to look at here is using data attributes so that you can later use .data() in jQuery. 这里要看的一件事是使用data属性,以便以后可以在jQuery中使用.data()

JavaScript JavaScript的

$(function() {
  function loadData() {
    var fd = localStorage.getItem("fd");
    if (fd != null) {
      return JSON.parse(fd);
    }
    return false;
  }

  function saveData(fd) {
    localStorage.setItem("fd", JSON.stringify(fd));
  }

  function get(item) {
    if (item == undefined) {
      item = "team"
    }
    var url;
    switch (item) {
      case "team":
        url = $("#gameForm").data("team-url");
        $.get(url, function(r) {
          $("#inputTeamId").val(r);
        });
        break;
      case "game":
        url = $("#gameForm").data("game-url");
        $.get(url, {
          'selected_teamid': $("#inputTeamId").val()
        }, function(r) {
          $("#inputGameId").val(r);
        });
    }
    saveData({
      'inputTeamId': $("#inputTeamId").val(),
      'inputGameId': $("#inputGameId").val()
    });
  }

  function loading(e) {
    e.preventDefault();
    saveData({
      'inputTeamId': $("#inputTeamId").val(),
      'inputGameId': $("#inputGameId").val()
    });
    // Loading script
  }

  function init() {
    var formData = loadData();
    if (formData) {
      $.each(formData, function(i, d) {
        $("#" + i).val(d);
      });
    } else {
      get("team");
    }
  }

  $("#inputTeamId").change(function() {
    get("team");
  });

  $("#gameForm").submit(loading);

  init();
});

This example makes use of localStorage to quickly store the form values. 本示例利用localStorage快速存储表单值。 The functions can easily be adjusted to use Cookies or pushing them to the server to be stored. 可以轻松调整功能以使用Cookies或将其推送到要存储的服务器。 This depends on your needs. 这取决于您的需求。

If the form has basic data, collecting it in to an object will be easy and helpful for storing. 如果表单具有基本数据,则将其收集到一个对象中将很容易并且有助于存储。 We can only store String data to localStorage , so we can use JSON.stringify() to convert the object into a String that we can parse later. 我们只能将String数据存储到localStorage ,因此我们可以使用JSON.stringify()将对象转换为String,以便稍后进行解析。

When the page loads, we can attempt to load the data. 页面加载后,我们可以尝试加载数据。 If there is no localStorage content, it will try to get a Team. 如果没有localStorage内容,它将尝试获得一个团队。 If there is data, it will set that data in the form elements by ID. 如果有数据,它将通过ID在表单元素中设置该数据。

In your script, you can collect the URLs using $("#gameForm").data('team-url') and $("#gameForm").data('game-url') . 在脚本中,您可以使用$("#gameForm").data('team-url')$("#gameForm").data('game-url') If your form gets more complex, you may consider using GET the data from one Script with a item passed to it. 如果您的表单变得更复杂,则可以考虑使用从一个脚本中获取数据并将其传递给项目。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM