javascriptjqueryjquery-selectorsparent-childparent-selector

How to fetch div value with specific id using Jquery?


I have list of data with add button . On button click how to get value of div with id="rnumber" with jquery .i want number on button click. i don't know how to get that number i try but every time i get first number of list i want number of same class . ex. if i click on second li button still i get first li class div value . I try with parents and child selector but i don't get anwser.

<div class="modal-body">
    <ul class="searchresult" style="list-style-type: none;">
        <li>
            <div  class="kt-font-lg">AKash</div>
            <div  class="kt-font-lg rnumber" >1234567890</div>
            <button  class="kt-font-lg btn-primary " onclick="addNumber()">Add</button>
        </li>
        <li>
            <div  class="kt-font-lg">Deep</div>
            <div  class="kt-font-lg rnumber" >9012345678</div>
            <button  class="kt-font-lg btn-primary " onclick="addNumber()">Add</button>
        </li>
    </ul>
</div>

onClick function :

function addNumber(){
                rnumber = $('#rnumber');
                var  ttt = rnumber.text();
                console.log(ttt);        
             }

Solution

  • You have to keep your IDs unique. Duplicating IDs is a crime. Change it to a class instead. Since multiple elements share the same function, use event.target or this. You can use something like this:

    function addNumber() {
      console.log($(event.target).prev().text());
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="modal-body">
      <ul class="searchresult" style="list-style-type: none;">
        <li>
          <div class="kt-font-lg">AKash</div>
          <div class="kt-font-lg rnumber">1234567890</div>
          <button class="kt-font-lg btn-primary" onclick="addNumber()">Add</button>
        </li>
        <li>
          <div class="kt-font-lg">Deep</div>
          <div class="kt-font-lg rnumber">9012345678</div>
          <button class="kt-font-lg btn-primary" onclick="addNumber()">Add</button>
        </li>
      </ul>
    </div>

    In a better way, use unobtrusive JavaScript event handling:

    $(function () {
      $(".btn-primary").click(function () {
        console.log($(this).prev().text());
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="modal-body">
      <ul class="searchresult" style="list-style-type: none;">
        <li>
          <div class="kt-font-lg">AKash</div>
          <div class="kt-font-lg rnumber">1234567890</div>
          <button class="kt-font-lg btn-primary">Add</button>
        </li>
        <li>
          <div class="kt-font-lg">Deep</div>
          <div class="kt-font-lg rnumber">9012345678</div>
          <button class="kt-font-lg btn-primary">Add</button>
        </li>
      </ul>
    </div>