Search code examples
jqueryinputjquery-selectors

How to clone the same input value to other inputs using JQuery?


I need to replicate a value (keyup) from an input to others, but only in a specific block. I get the ID from an item using a class selector and then I copy the value using a for loop. Why does console.log($('.claimed').attr('id')) keep writing the D1 value and ID?

<script>
    $(document).ready(function () {
       $(".claimed").keyup(function (e) {
          var claimed = $(this).val();
          var claimedid = $(".claimed").attr('id');
            console.log($('.claimed').attr('id'));
          for (var i = 0; i < 25; i++) {
             $("#" + claimedid + "S" + i).val(claimed);
          }
       });
    });
</script>


<?for($day=1;$day<=3;$day++){?>
    <div class="">
        <div>
            <?echo "D".$day;?>
            <input class="claimed" type="text" name="Claimed<?=$day?>" id="D<?=$day?>">
        </div>
        <?for($student=0;$student<3;$student++){?>
            <div class="">S<?=$student?>D<?=$day?>
                <input class=""  type="text" id="D<?=$day?>S<?=$student?>">
            </div>
        <?}?>
    </div>
<?}?>

Thanks in advance to anyone can help me and maybe simplify the jQuery.


Solution

  • I believe this line is the problem

    var claimedid = $(".claimed").attr('id');
    

    you have multiple input elements with that class.

    you can use $(this) instead as your event handler's scope is bound to the specific element that triggered the event.