skip to Main Content

In my php file I have a span under a button which in turn is inside a td

<td class="floating-td"><button class="count"><span id="compareCounts"><?php echo $listInfo; ?></span> </button></td>

At the end of the file while trying to fetch the value of span through ID I’m not getting anything. But when I check in the Chrome console, I do get the values there.

jQuery(document).ready(($) => {
   var countVal = $('#compareCounts').text();
   // var countVal = document.getElementById("compareCounts").value;
   console.log("qwerty countVal bc-html: ", countVal);
}

As shown above, I tried using JS and jquery, in both the cases I’m not getting the value while running the code. Though trying $('#compareCounts').text(); and document.getElementById("compareCounts").value in the console tab in Chrome does give the value.

What could be wrong here ?

2

Answers


  1. I think this will help you. I will try using jquery with on load and on button click how to get the value and console it.

    $(function() {
      // button click get value and console
      $(".count").click(function() {
          $('#compareCounts').text();
          console.log("btn click get value and console: ", countVal);
      });  
    
      // first time on load get value and console
      var countVal = $('#compareCounts').text();
      console.log("on page load get value: ", countVal);      
    });
    <html>
    <head>
      <title>Test Example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    </head>
    <body>
      <td class="floating-td">
        <button class="count">
          <span id="compareCounts">test</span>
        </button>
      </td>
    </body>
    </html>
    Login or Signup to reply.
  2. If you have multiple dynamic values at that time on btn click you can get the span value

    $(function() {
      $("button").click(function(e){
            var a = $.trim($(this).text());
          console.log(a);
      });
    });
    <html>
    <head>
      <title>Test Example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    </head>
    <body>
      <td class="floating-td">
        <button class="count">
          <span>test</span>
        </button>
      </td>
        <td class="floating-td">
        <button class="count">
          <span>test1</span>
        </button>
      </td>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search