How to use a tag property, using Jquery

Asked

Viewed 116 times

2

I have a dynamically filled component

<select id="selectTeste">
    <option value='1' exigeIdade='true'>item 1</option>
    <option value='2' exigeIdade='true'>item 2</option>
    <option value='3' exigeIdade='false'>item 3</option>
    <option value='4' exigeIdade='true'>item 4</option>
</select>

and I have a jquery function that needs to use the exigeIdade, ex:

//se alterar o comboProcedimento, verifica a idade
    $("#selectTeste").on("change", function () {
        atualizaProfissional(exigeIdade); //Como pegar a propriedade exigeIdade?
    });

How to send the demand property via parameter?

2 answers

6


Use the data attribute of HTML

To access a value from a date type attribute using jQuery use $('elemento').data('nome-atributo')

$("#selectTeste").on("change", function() {
  var exigeIdade = $("#selectTeste option:selected").data('exige-idade');
  console.log(exigeIdade);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectTeste">
    <option value='1' data-exige-idade='true'>item 1</option>
    <option value='2' data-exige-idade='true'>item 2</option>
    <option value='3' data-exige-idade='false'>item 3</option>
    <option value='4' data-exige-idade='true'>item 4</option>
</select>

  • In that case, all I have to do is add the word data- before the name of my attribute? can be data-exigeIdade?

  • 1

    May data-exigeIdade yes, but note that I wrote data-exige-idade, because HTML is case insensitive, and at the time of recovering this value you will have to use the whole name in case, that way - .data('exigeidade'). That’s why I used exige-idade, in addition to being a good practice for writing html tags/properties. :)

  • got it, thanks

  • It worked well in simple html, but when I use this code in bootstrap-select does not work. Any hint?

  • 1

    my mistake, it worked yes.

4

Try it like this:

$("#selectTeste").on("change", function () {
    var ExigeIdade = $("#selectTeste").find(":selected").attr("exigeIdade");
    atualizaProfissional(ExigeIdade);
});

Browser other questions tagged

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