Home > Software design >  Unable to get custom attribute value from span using Jquery
Unable to get custom attribute value from span using Jquery

Time:10-03

I am working with jquery,I want to get "custom attribute" value using jquery but right now i am getting "undefined" Here is my html code

<span  id="spanTest" data-value="<?php echo $nit['id'];?>" onclick="add_like(this)">
</span>

Here is my script

<script>
            function add_like()
                {
                    var dataId = $(this).val($(this).attr("data-value"));
                    alert(dataId);
                }
  </script>

CodePudding user response:

Please try this and check agian.

<span  id="spanTest" data-value="check data" onclick="add_like(this)">dev test
</span>

Replace js:

 <script>
            function add_like(){
                console.log(event.target.id);
                var dataId = $('#' event.target.id).attr("data-value");
                alert(dataId);
            }
  </script>

Another way, you can also try like below:

       <span  id="spanTest" data-value="<?php echo $nit['id'];?>"> <?php echo $nit['id'];?>
</span>



 <script>
 
            
            $(document).ready(function() {
                $(".spanTest").click(function(event) {
                    var dataId = $(this).attr("data-value");
                    alert(dataId);
                });
            });
  </script>

CodePudding user response:

How to get a custom attribute:

  • In vanilla js it will be something like this:
element.dataset.value // data-value
element.dataset.otherValue // data-other-value
  • In jQuery taking as reference .data():
$(selector).data('value') // data-value
$(selector).data('otherValue') // data-other-value

For this case it should work:

<span data-value="<?php echo $nit['id'];?>" onclick="add_like(this)"></span>

<script>
  function add_like(element) {
    var dataId = $(element).data("value"); // <?php echo $nit['id'];?>
  }
</script>
  • Related