How to get information from an option with Jquery/Javascript

Asked

Viewed 23 times

0

This select is an ajax, which I then receive and put into a modal. I needed to pass some values by select and then use them in addAtributo function activated by a button click

        <select class="form-control selectDropdown" id='listaAtributo'>
            <?
            foreach ($atributos as $ind => $v) {
                ?>
                <optgroup label="<?= $v['atributo']; ?>">
                    <option data-chave='<?= $v['atributo'];?>' data-id='<?= $v['id'];?>'><?= $v['valor']; ?></option>
                </optgroup>
            <? } ?>
        </select>

What I’ve tried but not sure, I can only catch the val(). I also tried to pass the values with onChange in select but as the values are within a foreach did not work, only this.value.

    function addAtributo() {
        var _atributo = $('#listaAtributo').val();
        var _id = $('#listaAtributo').attr("id");
        var _id = $('#listaAtributo').attr("data-chave");
        var _id = $('#listaAtributo').data("chave");
        var _listaAtributoChave = $('#listaAtributo').children(":selected").attr("id");
    }

How to proceed?

Thank you for your attention

1 answer

0

If you want to just take the data-id of option which is selected, just do (without Jquery):

window.document.querySelector("#listaAtributo").selectedOptions[0].dataset.id;

The .selectedOptions belongs to the HTMLSelectElement. The [0] is used because the select supports the multiple and I assume that this is not the case, obviously. You can also use the .selectedIndex in combination with the .options also.

For example:

let button = window.document.querySelector("button");
let output = window.document.querySelector("output");

button.addEventListener("click", function(_) {
  output.value = window.document.querySelector("#listaAtributo").selectedOptions[0].dataset.id;
});
<select class="form-control selectDropdown" id='listaAtributo'>
  <optgroup label="ATTR-1">
    <option data-chave='ATTR-1' data-id='ID-1'>Valor-1</option>
  </optgroup>
  <optgroup label="ATTR-2">
    <option data-chave='ATTR-2' data-id='ID-2'>Valor-2</option>
  </optgroup>
</select>

<button>SALVAR</button>

<output></output>

Browser other questions tagged

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