Assign dynamic value to a variable in Jquery

Asked

Viewed 436 times

1

I searched hard and I couldn’t find the answer.

I need to assign a value to a variable in Jquery, I don’t have much knowledge. What I need is:

By clicking on a link:

<a href="?sts=Pendente" title="Avisos Pendentes" id="Pendente" data-statusTipo="Pendente">

A variable called sts1 has the id value above:

var sts1 = $('a').on(click (function() {
  $('a:hover', this).data('statusTipo');
}));

That’s it... I’ve tried everything and I couldn’t...

Thank you for your attention

3 answers

2


When you use $('a').on(click (function() { jQuery calls this function when the element receives the event. Within this function the this receives an indicator for the element. Thus, within this function you can use:

var id = this.id; // para saber o id
var status = this.dataset.statusTipo; // para aceder a `data-`

So you can use:

$('a').on(click (function() {
    var id = this.id; // para saber o id
    var status = this.dataset.statusTipo; // para aceder a `data-`
    alert(id + ' ' + status);
}));
  • worked thanks for the return

  • I only had a question, for me to use this variable in another function I have to use without the "var"... that’s it?

  • @Exact thiagobuzatto. If you use the var you will re-start the variable and it loses the old value.

0

Try it like this:

$(document).ready(function() {
 var sts1 = '';

 $('a').click(function() {
   sts1 = $(this).data('statusTipo');
 });
});
  • thanks for the feedback, it worked yes, abs

  • Please mark the best answer as a solution

0

Friend, Jquery has a function called attr(). The syntax of the command is:

$( seletor ).attr( 'nome_atributo' );

Now to solve your problem, do:

$(document).ready(function() {
     var sts1 = '';

     $( 'a' ).click(function() {
         sts1 = $(this).attr( 'data-statusTipo' );
     });

});

I hope it helps you.

  • worked also, solved... abs and thanks

  • Choose the solution of +1 and 7 as the best answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.