How to select attributes and values in select

Asked

Viewed 93 times

1

How to select attribute (obligate) of the category that this set, Every time 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>  

1 answer

2


Can use selectedIndex (picks up the option selected) and getAttribute (takes the attribute). Then you can use the variable categorias to take 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, maybe it’s interesting to know about the subject in this question.

Browser other questions tagged

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