Calculating Machine Calculating Machine - 4 months ago 15
jQuery Question

Jquery on click not working while passing data

Question is very simple but due to some reason i am not able to fix it.
Here is the a href tag that will open modal box.

<center><a href="javascript:void();" class="btn-home" data="<?php echo $cid;?>" data-toggle="modal" data-target="#ApplyModal" name="btn-classified" id="btn-classified" href="#">Apply</a></center>


Here is jquery to get id from data attribute.

<script type="text/javascript">
$('document').ready(function()
{
$(document).on('click', '#btn-classified', function() {
//$("#btn-classified").on("click", function () {
//$("#btn-classified").click(function() {
var myvar1 = $(this).data('data');
alert(myvar1);

});
});
</script>


For some reason i am not getting any output if i use
$(document).on('click', '#btn-classified', function() {

and if i use
$("#btn-classified").on("click", function () {
then i am getting undefined.

Answer

To get 'data' attribute of <a> element use .attr() function of jQuery

  $('document').ready(function() {
    $(document).on('click', '#btn-classified', function() {
      var myvar1 = $(this).attr('data'); // .attr() to get attribute of an element
      alert(myvar1);
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' id='btn-classified' data='This an element of DOM'>Get this DATA value</a>

Your Code get undefined on event click when your call to an element which exist after of the function.

You need performance the logic of your code, on jQuery you want use

$(document).ready(function(){ 
 //your functions with selectors of DOM 
})

or use .on() function of jQuery to events.

$(document).on('click', '.mainButton', function(){
 //your code
})
Comments