Accessing value of inputs within a div in each()

随声附和 提交于 2019-12-24 19:16:41

问题


I have a bit of code that allows a user to add a new phone to a list like so

const addPhone = async (phone) => {
  $('.phone-list').append(`
  <div class='phone-div'>
    <table">
    <tbody>
      <tr>
        <td">
            <p>
              <input class='type' type='text' value='${phone.type}'></input>
            </p>
            <p>
              <input class='detail' type='text' value='${phone.detail}'></input>
            </p>
        </td>
      </tr>
    </tbody>
  </table>
</div>);
};

Each time a user adds a new phone a new phone-div is added tothe list and turns up on screen.

Now when the user taps a submit button I want to read the data from each phone-div create an object with and push that obj into an array that I can then send as JSON to my API to process... currently I am trying to use this

$(document)
  .on('click', '#submit', async () => {
    const phoneArray = [];
    $('.phone-div').each((i) => {
      console.log($(this).find('.type'));// returns undefined
      console.log($(this).find('.detail'));// returns undefined
    });
  });

How can I get this to put type and detail in an obj and then push it into an array that I can then send to the server like

phoneArray.push({
    type: $(this).find('.type').val(),
    detail: $(this).find('.detail').val(),
})

回答1:


You are .each()ing the elements with arrow function, which doesn't have its own bindings to the this keyword. Consider replacing it to normal function.

$(document).on('click', '#submit', async () => {
  const phoneArray = [];

//—————————————————————vvvvvvvv——      
  $('.phone-div').each(function() {
    console.log($(this).find('.type'));
    console.log($(this).find('.detail'));
  });
});



回答2:


It's probably because you're using arrow functions and this doesn't refer to the element.

Either change your arrow function to a use function keyword or use the second parameter of the each callback to get the current element in context:

$(document).on('click', '#submit', async () => {
    const phoneArray = [];
    $('.phone-div').each((index, element) => {
        phoneArray.push({
           type: $(element).find('.type').val(),
           detail: $(element).find('.detail').val(),
         })
    });
});



回答3:


I don't know what you expected using async. A "normal" function perfectly does the job.

And a fixed a couple typos in the .append()...

function addPhone(phone){
  $('.phone-list').append(`
    <div class='phone-div'>
      <table>
        <tbody>
          <tr>
            <td>
              <p>
                <input class='type' type='text' value='${phone.type}'></input>
              </p>
              <p>
                <input class='detail' type='text' value='${phone.detail}'></input>
              </p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  `);
}

$(document).on('click', '#submit', function(){
  const phoneArray = [];
  $('.phone-div').each(function(i){
    console.log($(this).find('.type').val());
    console.log($(this).find('.detail').val());

    phoneArray.push({
      type: $(this).find('.type').val(),
      detail: $(this).find('.detail').val(),
    })
  });
  console.log(phoneArray);
});

$("#add").on("click",function(){
  // just for the demo... Since I can't know where this object comes from...
  var phone = {type:"cellular",detail:"1-888-555-5555"}
  addPhone(phone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="phone-list"></div>
<button id="add">Add</button>
<button id="submit">Submit</button>


来源:https://stackoverflow.com/questions/54427058/accessing-value-of-inputs-within-a-div-in-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!