简体   繁体   English

从下拉选项填充表单输入,解析 json 数据属性

[英]Populate form inputs from dropdown options, parsing json data attributes

A select dropdown menu is populated after a MySQL query, yielding something like在 MySQL 查询之后填充一个选择下拉菜单,产生类似

<form method="post" action="action.php">
   <select name="elements" id="elements">
      <option type="text" value="">Select an element to be modified, or fill data below for a new one</option>
      <option type="text" value="1" data-json='{"elements_id":"1","elements_field1":"Lorem ipsum","elements_field2":"Foo"}'>Element 1</option>
      <option type="text" value="2" data-json='{"elements_id":"2","elements_field1":"Lorem ipsum again","elements_field2":"Foo again"}'>Element 2</option>
   </select>
   <input type="text" id="elements_id">
   <input type="text" id="elements_field1">
   <input type="text" id="elements_field2">
   <input type="submit" value="Submit">
</form>

I would like that the various input fields be populated dynamically according to the selection in the droplist above.我希望根据上面下拉列表中的选择动态填充各种输入字段。

Following suggestions found here , I've tried including the following script in the <head> section of my php file:按照此处找到的建议,我尝试在我的 php 文件的<head>部分中包含以下脚本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $('#elements').on('change', function() {
       var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
       $('#elements_id').val(selected.elements_id);
       $('#elements_field1').val(selected.elements_field1);
       $('#elements_field2').val(selected.elements_field2);
   });
</script>

But this does not work, and does not even result in an error which I can track through the browser's Web Console.但这不起作用,甚至不会导致我可以通过浏览器的 Web 控制台跟踪的错误。 I presume it has to do with the json formatting coming as an output of a MySQL query (not shown, but validated as a regular json), or with the json parsing by the script.我认为它与作为 MySQL 查询输出的 json 格式有关(未显示,但已验证为常规 json),或与脚本解析的 json 有关。

Any hint or suggestion?任何提示或建议? Many thanks!非常感谢!

Your code seems to work for me.你的代码似乎对我有用。 The only mistake is that you are setting the value of the second input twice.唯一的错误是您将第二个输入的值设置了两次。 Fixing that, here's a JS Bin .解决这个问题,这是一个 JS Bin

$('#elements').on('change', function() {
  var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
  console.log( selected );
  $('#elements_id').val(selected.elements_id);
  $('#elements_field1').val(selected.elements_field1);
  $('#elements_field2').val(selected.elements_field2); // <-- Here was your error
});

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

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