Grab Id and move to another function on click button

Asked

Viewed 892 times

4

Galley,

I have the following problem, I have a table and every record I have a link.

By clicking on this link I take the ID as follows and call a modal.

<script>
 $(document).on("click", "a", function(){
    if ($(this).hasClass("clique")) {
        var id = $(this).attr('id');
        $('#md-default').modal('show');
    }
 });
</script>

In this modal I have a confirmation button, how can I get the id I clicked on the link? There is how to declare a global variable and store the ID value in it and then recover by clicking the other button?

<script>
$('#submitButton').click(function() {
alert("Como pegar o ID alterior??");

}
</script>
  • Could you add this value to an Hidden input for example? Is this an input or a link? You cannot pass the parameter by GET?

2 answers

3


If you choose to add to the global scope could do something like:

<script>
 var idSel;
 $(document).on("click", "a", function(){
    if ($(this).hasClass("clique")) {
        idSel = $(this).attr('id');
        $('#md-default').modal('show');
    }
 });

 $('#submitButton').click(function() {
    console.log(idSel);
 });
</script>

 var idSel;
 $(document).on("click", "a", function(){
    idSel = $(this).attr('id');
 });

 $('#submitButton').click(function() {
    console.log(idSel);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="link">Clique em mim</a>
<br/><br/>
<button id="submitButton" >Ok</button>

  • 1

    You’re right Lucas, I’ll do according to your tip. Thank you!

3

I suggest you pass the ID to a data field of the element that does Submit.

This avoids global variables and the button you confirm has the information you should have. Also note the class setting clique, who thus dispenses with if unnecessary.

$(document).on("click", "a.clique", function(){
    $('#submitButton').data('id', this.id);
    $('#md-default').modal('show');
});
$('#submitButton').click(function() {
    var id = $(this).data('id');
    alert(id);
});

Browser other questions tagged

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