Save data attribute data to an Hidden input

Asked

Viewed 94 times

0

I have a form and would like to take the values of the 'data-aliquot' attributes and put inside an invisible input. I don’t know how I can do it.

<form>
  <input type="text" id="cidade" data-aliquota="1.00" name="cidade" value="salvador" />
  <input type="text" id="estado" data-aliquota="2.00" name="estado" value="bahia" />
  <input type="hidden" name="valores" id="valores" />
</form>

The way out should be something like: "1.00,2.00"

  • use attr do jQuery http://api.jquery.com/attr/

1 answer

0


You can use the function date to take the aliquot values. In the example I stored all aliquots in an array and inserted that array into the input hidden

window.onload = function(){
    var aliquotas = [];
    $("input").each(function(){
        if($(this).data("aliquota") >= 0){
            aliquotas.push($(this).data("aliquota"));
        }
    });
    
    $("#valores").val(aliquotas);
    
    console.log($("#valores").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" id="cidade" data-aliquota="1.00" name="cidade" value="salvador" />
  <input type="text" id="estado" data-aliquota="2.00" name="estado" value="bahia" />
  <input type="hidden" name="valores" id="valores" />
</form>

  • It worked perfectly, @Jrd. Thank you.

Browser other questions tagged

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