简体   繁体   中英

How to set value at input text field

I have this below code. I can display the list of JSON file but I can't click the items of the list. Could you teach me How to add click and store item function. What I would like to do is click the item of the list .After click it "NAME" value store the textbox. so then After set the value Click submit buttom then pass the NAME and related data. For example. Fist data https://api.myjson.com/bins/8x0ag

Fist data name is orange. When user click the orange. and press submit button I would like to send the code "102" and location "N34" data to Next page.

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

Actually I had another code. To select item and store the value into the text field. but I changed the code after that I lost selecting function.

$(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>`
        )
      });
    },
  }
})($);

I tried to add this code to above but it doesn't work.

$('#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+'">');    
});

Mainly you need an event handler for the onClick for the li items.

It sets the name as value in the visible fields and creates hidden inputs in the form where you may have as much variables as you like but serialized in any way

Here is your working example

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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