Select an option with external button

Asked

Viewed 57 times

0

Good afternoon, everyone,

I need that when I press a button, the same cause a specific option is selected on select. For example, I own 3 buttons and 3 buttons options:

<button>1</button>
<button>2</button>
<button>3</button>

<br><br>

<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

If I click the button 1 will select the option 1, if I click the button 2 will select the option 2, and if I click the button 3 will select the option 3.

I don’t know much about Javascript, but I think I’ll probably need to use.

I appreciate any help.

1 answer

1


My tip is to put an ID on each btn, and option vc puts the value equal to the ID value, type o btn1, has the id=n1, and the option1 has the value=n1, so vc says value should be = to the id of the clicked element, simple like this, see

inserir a descrição da imagem aqui

let btn = document.querySelectorAll('button');
let select = document.querySelector('select');

function troca(e) {
    select.value = e.currentTarget.id;
}

btn.forEach( (el) => {
    el.addEventListener('click', troca);
}) 
<button id="n1">1</button>
<button id="n2">2</button>
<button id="n3">3</button>

<br><br>

<select>
    <option value="n1">1</option>
    <option value="n2">2</option>
    <option value="n3">3</option>
</select>

  • 1

    Just what I needed, thank you!

  • @Jeanfranz opa! Cool that solved ai :D was worth the strength!

  • if it’s a tag a change something or just change the button for a?

  • @Jeanfranz changes yes, you can use href as a reference instead of id for example, and put e.preventDefault in the pro link function not to interfere, or else vc puts id in A and leaves href=# even, theoretically it will work normal

Browser other questions tagged

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