skip to Main Content

I am a beginner learning javascript.

$('.btn').on('click', function(){
    let i = 0;
    while (i < 5) {
        $(this).closest('.number').val(i)
        i++;
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="btn">Sort</div>

<input type="text" class="number" data-id="1" value="1">
<input type="text" class="number" data-id="5" value="5">
<input type="text" class="number" data-id="4" value="4">
<input type="text" class="number" data-id="3" value="2">
<input type="text" class="number" data-id="2" value="3">

My Output:

<div class="btn">Sort</div>

<input type="text" class="number" data-id="1" value="1">
<input type="text" class="number" data-id="5" value="2">
<input type="text" class="number" data-id="4" value="3">
<input type="text" class="number" data-id="3" value="4">
<input type="text" class="number" data-id="2" value="5">

when click on .btn,it all value sort:1,2,3,4,5 is not saved.
Help me solve this problem.

2

Answers


  1. If I understand correctly, you want the "button" to update the values of the input elements, in order from 1-5?

    For starters, you’re misunderstanding that .closest() does. It looks for the "closest" matching element up the DOM hierarchy. The .number elements are not parents/ancestors of the .btn element, so none of them will match.

    You can find the .number elements with simply: $('.number')

    Then you can use .each() to loop over those elements. The first argument to the callback is the index of that element in the resulting collection. It’s zero-based, so just add 1 to it. For example:

    $('.btn').on('click', function(){
      $('.number').each(function(i) {
        $(this).val(i + 1);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="btn">Sort</div>
    
    <input type="text" class="number" data-id="1" value="1">
    <input type="text" class="number" data-id="5" value="5">
    <input type="text" class="number" data-id="4" value="4">
    <input type="text" class="number" data-id="3" value="2">
    <input type="text" class="number" data-id="2" value="3">
    Login or Signup to reply.
  2. A simpler method over looping with .each is to pass a callback function to .val, the first argument to which is the index.

    $('.btn').on('click', () => $('.number').val(i => i + 1));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="btn">Sort</div>
    <input type="text" class="number" data-id="1" value="1">
    <input type="text" class="number" data-id="5" value="5">
    <input type="text" class="number" data-id="4" value="4">
    <input type="text" class="number" data-id="3" value="2">
    <input type="text" class="number" data-id="2" value="3">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search