0

I have a button

<button type="button" data-id="5" class="get_attr" >Click Me</button>

and i want to get the data-id value then i write the code

<script type="text/javascript">
    $(".get_attr").on("click",function(){
        var id = $(this).data("id");
        console.log("id = "+id);  //id = 5
    });
</script>

Suppose I want this value, or do any functionality on this button from another function if i call function from this code like and I want like this:

<script type="text/javascript">
    $(".get_attr").on("click",function(){
        updateValue(this);
    });

    function updateValue(this){ // it will take it as a parameter
        var id = $(this).data("id");
        console.log("id = "+id);  //id = 5
    }
</script>
clauub
  • 1,134
  • 9
  • 19

4 Answers4

4

You can not use 'this' becasue it is Javascript keyword

<script type="text/javascript">
$(".get_attr").on("click",function(){
    updateValue(this);
});

function updateValue(abc){ // it will take it as a parameter
    var id = $(abc).data("id");
    console.log("id = "+id);  //id = 5
}

Now its work fine...

Rahul Sahu
  • 235
  • 1
  • 6
2

Being this is a reserved word, change the parameter name from this to some other like in updateValue(thatObj).

$(".get_attr").on("click",function(){
  updateValue(this);
});

function updateValue(thatObj){
  var id = $(thatObj).data("id");
  console.log("id = "+id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" data-id="5" class="get_attr" >Click Me</button>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You cannot use a reserved keyword in your function definition. It should work with simply using another name in the definition.

<script type="text/javascript">
        $(".get_attr").on("click",function(){
            updateValue(this);
        });

        function updateValue(originalObject){ // it will take it as a parameter
            var id = $(this).data("id");
            console.log("id = "+id);  //id = 5
        }
    </script>
rypskar
  • 2,012
  • 13
  • 13
1

Try this

    $(".get_attr").on("click",function(){
        var id = $(this).data("id");
        console.log("id = "+id);  //id = 5
    });



    $(".get_attr").on("click",function(){
        updateValue(this);
    });

    function updateValue(x){ // it will take it as a parameter
       var id = $(x).data("id");
        console.log("id = "+id);  //id = 5
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" data-id="5" class="get_attr" >Click Me</button>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34