如何在输入文本字段中设置值

时间:2019-02-12 12:26:47

标签: javascript jquery json ajax

我有下面的代码。我可以显示JSON文件列表,但不能单击列表中的项目。您可以教我如何添加点击和存储项目功能。 我想做的是单击列表中的项目。单击后,“名称”值存储文本框。因此,在设置值之后,单击“提交”按钮,然后传递名称和相关数据。例如。拳头数据https://api.myjson.com/bins/8x0ag

拳头数据名称为橙色。当用户单击橙色时。然后按提交按钮,我想将代码“ 102”和位置“ N34”数据发送到下一页。

name     "orange"
code     "102"
location "N34"

实际上我有另一个代码。选择项目并将值存储在文本字段中。但是在丢失选择功能之后,我更改了代码。

$(document).ready(function() {
  Main.init();
});

var Main = (function($) {
  return {
    vars: { },
    init: function() {
      Main.build();
      Main.events();
    },
    events: function() {
      $(document).on('keyup', '.search', function() {
        const ref = $(this).attr('data-ref');
        const {
          vars
        } = Main;
        $(`.resultUl[data-ref="${ref}"]`).html('');
        const searchField = $(this).val();
        const expression = new RegExp(searchField, "i");

        $.each(vars.JSONdata, (key, value) => {
          const {
            name,
            location,
            code,
            image
          } = value;
          if (name.search(expression) != -1 || location.search(expression) != -1) {
            $(`.resultUl[data-ref="${ref}"]`).append(
              `<li class="list-group-item link-class"
                   data-name="${name}"
                   data-code="${code}"
                   data-location="${location}">
               <img src="${image}" height="40" width="40" class="img-thumbnail" />
               ${name}
               <span class="text-muted">${location}</span>
             </li>`
            );
          }
        });
      });
    },
    build: async function() {
      JSONdata = await this.getJson();
      this.vars = {
        JSONdata
      };
      this.generateFields(20);
    },
    getJson: () => new Promise((resolve, reject) => {
      $.getJSON('https://api.myjson.com/bins/8x0ag', (data) => {
        resolve(data);
      }).fail(function() {
        reject([]);
      })
    }),
    generateFields: (fieldNumber) => {
      Array(fieldNumber).fill().map((v, i) => {
        const ref = i + 1;
        $('#container').append(
          `<div class="fieldContainer">
             <div class="btn-group">
               <input type="text" class="search" data-ref="${ref}" placeholder="" class="form-control" size="3000" onkeypress="return event.keyCode!=13" />
               <span class="searchclear glyphicon glyphicon-remove-circle"></span>
             </div>
             <ul class="list-group resultUl" data-ref="${ref}"></ul>
           </div>`
        )
      });
    },
  }
})($);

我试图将这段代码添加到上面,但是不起作用。

$('#result').on('click', 'li', function() {
var name = $(this).data('name' ); 
var code = $(this).data('code' ); 
var location = $(this).data('location' ); 

var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');


$('#result').after('<input type="hidden" name="name" value="'+name+'">');
$('#result').after('<input type="hidden" name="code" value="'+code+'">');
$('#result').after('<input type="hidden" name="location" value="'+location+'">');    
});

1 个答案:

答案 0 :(得分:1)

对于event项目,onClick主要需要一个li处理程序。

它将名称设置为可见字段中的值,并在hidden中创建form输入,您可以在其中输入任意数量的变量,但是可以通过任何方式对其进行序列化

这是您的工作示例

$(document).ready(function() {
  Main.init();
});

var Main = (function($) {
  return {
    vars: {

    },
    init: function() {
      Main.build();
      Main.events();
    },
    events: function() {
      $(document).on('keyup', '.search', function() {
          const ref = $(this).attr('data-ref');
          const {
            vars
          } = Main;
          $(`.resultUl[data-ref="${ref}"]`).html('');
          const searchField = $(this).val();
          const expression = new RegExp(searchField, "i");

          $.each(vars.JSONdata, (key, value) => {
            const {
              name,
              location,
              code,
              image
            } = value;
            if (name.search(expression) != -1 || location.search(expression) != -1) {
              $(`.resultUl[data-ref="${ref}"]`).append(
                `<li 
          					class="list-group-item link-class list-item"
          					data-name="${name}"
          					data-code="${code}"
          					data-location="${location}"
        					>
          				<img src="${image}" height="40" width="40" class="img-thumbnail" />
          				${name}
          				<span class="text-muted">${location}</span>
        			 </li>
               `
              );
            }
          });
        }),
        $(document).on('click', '.list-item', function() {
          const ul = $(this).closest('ul');
          const ref = $(ul).attr('data-ref');
          const name = $(this).attr('data-name');
          const location = $(this).attr('data-location');
          const code = $(this).attr('data-code');
          const hiddenInput = $(`.hiddenField[data-ref=${ref}]`);
          //console.log(hiddenInput.length);
          $(`.search[data-ref=${ref}]`).val(name);
          if (hiddenInput.length) {
            $(hiddenInput).val(`${name}_${location}_${code}`);
          } else {
            $('#submitForm').append(
              `<input 
                 type="hidden" 
                 class="hiddenField" 
                 data-ref="${ref}"
                 name="search_${ref}" 
                 value="${name},${location},${code}}"
             />
            `
            )
          }
          $(ul).html('');
        })
    },
    build: async function() {
      JSONdata = await this.getJson(); //JSONdata is a global variable which you can access from everywhere
      this.vars = {
        JSONdata
      };
      this.generateFields(20);
    },
    getJson: () => new Promise((resolve, reject) => {
      // Change the path below with the path for your script
      $.getJSON('https://api.myjson.com/bins/lpizs', (data) => {
        resolve(data);
      }).fail(function() {
        reject([]);
      })
    }),
    generateFields: (fieldNumber) => {
      Array(fieldNumber).fill().map((v, i) => {
        const ref = i + 1;
        $('#container').append(
          `<div class="fieldContainer">
    <div class="btn-group">
      <input type="text" class="search" data-ref="${ref}" placeholder="製品 その1" class="form-control" size="3000" onkeypress="return event.keyCode!=13" />
      <span class="searchclear glyphicon glyphicon-remove-circle"></span>
    </div>
    <ul class="list-group resultUl" data-ref="${ref}"></ul>
    </div>`
        )
      });
    },

  }
})($);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<head>
  <title>JQuery</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body>
  <br /><br />
  <div class="container" style="width:900px;">
    <h2 align="center"></h2>
    <h3 align="center"></h3>
    <br /><br />
    <div align="center">
      <div id="container">

      </div>
      <br />
      <form action="recive.php" method="post" id="submitForm">
        <input type="submit" id="submit" />
      </form>
    </div>


    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>