Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - Jquery Problem Input Reading Value Problem

I have problem with jquery getting input data when i created new input with jquery

I need get value from ID: 2 but i get test 1 John and from ID 2 test 2 undefined

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputs">
  <div class="names" id="1"><input type="text" id="Name"></div>
</div>
</br>
</br>
<a onclick="AnotherInput();">[+] Input</a>

<button onclick="send();">Send</button>

<div class="data">

</div>


<script>
  var inputs = 1;

  function AnotherInput() {
    inputs++;
    $('#inputs').append('<div class="input" id="' + inputs + '"><input type="text" id="Name"></div>');
  }


  function send() {

    var max = 0;
    $('.names').each(function() {
      max = Math.max(this.id, max);
    });


    for (var i = 1; i <= max; i++) {
      $('div#names').each(function() {
        $(".data").append(" test " + i + " " + $(this).find('div#' + i).find('select[id="Name"]').val());
      });
    }

  }
</script>
question from:https://stackoverflow.com/questions/65938939/jquery-problem-input-reading-value-problem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • Don't use IDs for your duplicated elements.
  • Don't use inline JS on* handlers attributes. Same as you hopefully don't use inline CSS style attribute.
  • To get a count of your current elements you could use .children().length

const
  $inputs = $("#inputs"),
  $add = $("#add"),
  $send = $("#send"),
  $data = $("#data");

function add() {
  const n = $inputs.children().length + 1;
  $inputs.append(`<div><input type="text" name="name_${n}"></div>`);
}

function send() {
  const data = $inputs.find('[name^="name_"]').get().map(el => el.value);
  $data.append(data.join("<br>"));
}

$add.on("click", add);
$send.on("click", send);
add(); // Init! (Add the first input)
<div id="inputs"></div>
<button type="button" id="add">+ Add</button>
<button type="button" id="send">&rarr; Send</button>
<div id="data"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...