How to select attributes and values in select

1

How to select attribute (oblige) of the category that is set, Whenever I click the button !!

var btn = document.querySelector("#btn");
var categorias = document.querySelector("#categorias");


btn.addEventListener("click", selecObriga);

function selecObriga(e){
  e.preventDefault();
  
  
 }
<form>
  <select id="categorias" name="categorias">
    <option value="1" obriga="0">Cores</option>
    <option value="2" obriga="1">Animais</option>
  </select>
  <input id="btn" type="submit">
</form>  
    
asked by anonymous 17.03.2018 / 22:18

1 answer

2

You can use selectedIndex (takes option selected) and getAttribute (takes attribute). Then you can use the variable categorias to get the values of select :

var btn = document.querySelector("#btn");
var categorias = document.querySelector("#categorias");

btn.addEventListener("click", selecObriga);

function selecObriga(e){
  e.preventDefault();
  
  var attr = categorias.options[categorias.selectedIndex].getAttribute('obriga');
  console.log(attr);
}
<form>
  <select id="categorias" name="categorias">
    <option value="1" obriga="0">Cores</option>
    <option value="2" obriga="1">Animais</option>
  </select>
  <input id="btn" type="submit">
</form>
  

As for using any name as an attribute name, it might be   interesting to hear about   question .

    
17.03.2018 / 22:44