单击时从特定<li>标记填充表单

时间:2018-02-21 18:35:57

标签: javascript jquery html

我有一个程序,它接受用户输入并过滤API并以<li>标记的形式返回结果。 API的结果可能大于1,000,因此我希望用户能够点击特定结果并填充<form>

一切正常,但如果我有多个结果,请尝试点击特定的<li>,我的input标记会填充来自的每个页面上 <li>。我错过了什么?

这是<li>

`
  <li class="populate">
    <span class="name" data-key="name">${place.Name}</span>
    </br>
    <span class="address" data-key="address">${place.Address}</span> <span class="city" data-key="city">${place.City}</span> 
    </br> 
    <span class="state" data-key="state">${place.StateProvince}</span> 
    <span class="postal-code" datakey="postal-code">${place.PostalCode}</span>
    </br> 
    <span class="country" data-key="country">${place.Country}</span>
    </br>
    <span class="dot-code" data-key="dot-code"><span class="highlight">${dotCode}</span></span>
  </li>
`

这是我的html代码所在的<li>

<form class="search-form">
    <input type="text" class="search" placeholder="Plant name">
    <ul class="suggestions">
      <li>Results will show here</li>
    </ul>

这是我填充的<form>

  <form class="upload-form">
    <input type="text" class="form-two f_code" placeholder="DOT Code" name="dot-code">
    <input type="text" class="form-two f_plant" placeholder="Plant" name="name">
    <input type="text" class="form-two f-add1" placeholder="Address" name="address">
    <input type="text" class="form-two f_add4" placeholder="State" name="state">
    <input type="text" class="form-two f_city" placeholder="City" name="city">
    <input type="text" class="form-two f_zip" placeholder="Zip Code" name="postal-code">
    <input type="text" class="form-two f_cntry" placeholder="Country" name="country">
  </form>

最后,这是我填充<form>的地方。在引用jQuery文档之后,我认为.index()是一种可能的解决方案,但是我不太确定如何实现它,或者这甚至是一个适用的场景。我在.index()之后尝试使用.text(),但我知道这不是有效的。

$('.suggestions li').click(function() {
  $('.upload-form').children().each(function() {
    let key = $(this).attr('name');
    let txt = $('.populate span[data-key="'+ key +'"]').text();

    $(this).val(txt);
  });
});

一些免责声明:我已经编程了一年多,而且我已经专业编程了大约两个月,所以如果我错过了一些细节,我会道歉。

2 个答案:

答案 0 :(得分:1)

$('.suggestions li').click(function() {
    //keep track of the li that was clicked
    var $li = $(this);

    $('.upload-form').children().each(function() {
        //this was doing a global lookup on the populate.
        //don't do this.  you already have your specific li
        //let txt = $('.populate span[data-key="'+ key +'"]').text();
        let txt = $li.find('span[data-key="'+ this.name +'"]').text();
        //or since the spans class matches the data-key you could use that
        let txt = $li.find('.'+ this.name).text();


        this.value = txt;
    });
});

答案 1 :(得分:1)

您缺少的部分是您点击的li的$(this)。你可以尝试这样的事情。

$('.suggestions li').click(function() {
   $(this).children('span').each(function() {
      let key = $(this).attr('data-key');
      let txt = $(this).text();          

      $('.upload-form[name="' + key + '"]').val(txt);
   });
});