【问题标题】:Saving/Storing the name of a selected option from an optgroup保存/存储来自 optgroup 的选定选项的名称
【发布时间】:2017-03-20 17:22:10
【问题描述】:

所以目前我有一个下拉菜单,其中填充了一个 json 文件,每个选项看起来都像这样(实际文件中有更多集合):

JSON

{
  "thing": {
    "Selected thing": [
      {
        "name"   : "thing 1",
        "value"  : 1.0,
        "purpose": "thing 1"
      }, 
    ]           
  }
}      

它们正在使用脚本填充到下面的 HTML 选择中:

HTML

<tr>
  <td><strong>Choose a Thing</strong></td>
  <td>
    <div>
      <select name="thing" class="form-control" id="thing" value="{{ thing  }}">
        <option class ="placeholder">{{ thing }}</option>
      </select>
    </div>
  </td>
</tr>

JavaScript

$(document).ready(function () {
  var menu = document.getElementById('thing')
  $.getJSON("{{ url_for('static', filename='things.json') }}", function (data) {
    $.each(data.things, function (optgroup, options) {
      var next_optgroup = document.createElement('OPTGROUP')
      next_optgroup.setAttribute("label", optgroup)
      menu.appendChild(next_optgroup)
      $.each(options, function (index) {
        next_option = document.createElement('OPTION')
        next_option.setAttribute("value", options[index].value)
        next_option.setAttribute("name", options[index].name)
        next_option.innerHTML = options[index].name
        next_optgroup.appendChild(next_option)
      });
    });
  });
})

因此,目前,一旦选择了选定的选项并按下了提交按钮,值 (1) 就会传递给 Flask 并通过 {{ thing }} 存储并呈现给选择选项值。

我需要它正常工作,但我还需要能够存储与所选选项关联的名称,我觉得我可能需要使用 javascript 或一些隐藏的输入(肯定在我的HTML 表单)来做到这一点,尽管我对 javascript 的了解很少。

换句话说,我如何能够存储并在刷新页面时保持选定的选项名称(事物 1)显示在 HTML 页面上?

【问题讨论】:

标签: javascript jquery html json flask


【解决方案1】:

链接中描述的本地存储 (https://www.w3schools.com/html/html5_webstorage.asp) 可用于在本地计算机上的用户浏览器中存储数据。这意味着如果他们从不同的计算机访问该页面,他们将无法访问该存储的数据。如果您需要保留这些信息并从不同的机器/浏览器访问它,那么您必须在实时 Web 服务器上实现一个数据库,并在用户点击页面时请求此信息。

本地存储使用简单。以下是如何为用户选择的事物设置变量的示例:

// Using jQuery
$('#thing').on('change', function() {
// Save the Value in local storage
localStorage.setItem('userThing', $('#thing').val());

});

在页面准备好并且您已构建并填充“事物”选择表单元素后从存储中加载值:

// Get the 'userThing' from local storage and set the select element with id 'thing'
$('#thing').val(localStorage.getItem('userThing');

这些任务对于 Javascript 开发人员来说很常见。已经构建了诸如 Google 的 AngularJS 和 Facebook 的 React 之类的框架来简化这些任务(也就是说,在您学习了该框架之后,它们很容易做到……这需要一点时间才能感觉舒适,但如果您愿意,那么付出努力是值得的打算使用 javascript 构建大型项目)。他们严重依赖 MVC 范式,在开发 Web 应用程序时强烈推荐这种范式。

【讨论】:

  • 谢谢马特我很欣赏你的回应,虽然这不是我所追求的选择选项的价值。我可以使用 Flask 存储选定的值,并使用 Jinga2 让它重新出现在表单上,​​尽管我不确定如何获取名称“thing 1”,其名称在提交后不会成为选择名称。我觉得我可能需要对下拉列表的索引做一些事情,然后遍历 json 文件以找到归属于该索引的名称,尽管我并不肯定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多