Assign value from a JS variable to an HTML element?

Asked

Viewed 71 times

-1

Next, I assigned a value to a button, and passed to my function through the onClick. Only now, I’d like to take that amount that’s in index and input my modal... How can I do this?

My button that calls the function:

<button data-var="<?= $cont ?>" onClick="funcaoModal(this)" class="dropdown-item" data-toggle="modal" data-target="#modal-atualizar">Atualizar></button>

My job:

function funcaoModal(element) {
        var index = $(element).data('var');
        
        
    }

My modal:

<div class="modal fade" id="modal-atualizar">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">Atualizar</h4>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <form action="solicitacao.php" method="POST">
                                    <div class="form-group">
                                        <label class="input-form col-md-6" for="ticket">Número do ticket:</label>
                                        <input class="input-form form-control col-md-12" type="text" id="ticket" name="ticket" value=""  readonly>
                                    </div>

I wanted the value of the variable to be pro value of my input, of the modal.

1 answer

0


Opa, you did almost everything right, just need to change the way you’re trying to access the attribute data-var, would be with the method .attr(), q hence you pass the attribute name and arrow/redeem its value

function funcao(element) {
  var dataVar = $(element).attr('data-var')
  $('input').val(dataVar)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-var="15" onclick="funcao(this)">Clique</button><br>
<input type="text">

  • Thanks Mt Andre, it worked! I only had a doubt, that date-var I did not know, I saw in another tutorial. I can pass more than one element on it? If I wanted to pass more than one datum for example, would I?

  • Good!! Look, this one data-var was a custom attribute that the tutorial used, you can have as many as you want, and call them as you want tbm, id-produto for example, already about passing more than one element, as if it were an array, I think q not, but from there passing multiple attributes maybe solve for you

Browser other questions tagged

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