2

I created a div dynamically, and on click event I want to get it's attribute value, but when I try to do that, it throws me an error. "jQuery(...).attr(...).val is not a function", refer my code below

    jQuery("#target1").on("click", function(){
        jQuery("#target_block").append('`<div id="target2" data-rel-pid="12345">Click Me</div>`');
    });

    jQuery("#target2").on("click", function(){
        var bid=jQuery(this).attr("data-rel-pid").val();
    });
2
  • Remove .val() from that line. Commented Jan 27, 2016 at 6:16
  • Is handler being invoked, I suspect it will not.. Commented Jan 27, 2016 at 6:24

5 Answers 5

2

Actually the error is in this line :

var bid=jQuery(this).attr("data-rel-pid").val();

There is no need to cal .val() on .attr()

var bid=jQuery(this).attr("data-rel-pid");

.attr() itself will return the value.

For more to this, refer here.

Sign up to request clarification or add additional context in comments.

Comments

2

Remove the .val()

jQuery("#target2").on("click", function(){
var bid=jQuery(this).attr("data-rel-pid");
});

Comments

2

As you are already using jQuery and you want to fetch a data attribute you can also do something like this.

$("#target2").on("click", function(){
 var bid=$(this).data("rel-pid");
});

Comments

1

As target2 is being appended later in the life cycle of the web page, you need to use event delegation to attach event to dynamically appended elements.

Remove .val(), Use .attr() to get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

Try this:

jQuery("#target1").on("click", function() {
  jQuery("#target_block").append('<div id="target2" data-rel-pid="12345">Click Me</div>');
});

jQuery("#target_block").on("click", '#target2', function() {
  var bid = jQuery(this).attr("data-rel-pid");
  alert(bid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="target1">target1</div>
<div id="target_block">target_block</div>

Comments

1

You can use this code -

jQuery("#target2").on("click", function(){
    var bid = jQuery(this).data("rel-pid");
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.