简体   繁体   中英

How to add selected attribute when selecting an option?

I have a select in which I add an option dynamically, depending on the number of elements in the database. How can I add a selected attribute on selection so that the user's selection can be tracked

 function generateBanks(banks) { banks.forEach((bank) => { const bank_option = document.createElement("option"); bank_option.value = bank.bankName; bank_option.text = bank.bankName; bankSelect.appendChild(bank_option); }); }

 function getAllBanks() { db.collection("banks").onSnapshot((snapshot) => { let banks = []; snapshot.docChanges().forEach((change) => { const bank = { id: change.doc.id, ...change.doc.data(), }; banks.push(bank); generateBanks([bank]); }); }); }

If I'm understanding correctly what you asked, you can have an id as value of each option of the select element. For a better explanation I'll show a little example:

 let payment = document.getElementById('payment'); const calculate_button = document.getElementById('calculate-button'); const bank_select = document.getElementById('bank-select'); calculate_button.addEventListener('click', () => { const bank_id_selected = bank_select.value; // Do a query to your db with the `bank_id_selected`, here substituited by a `random()` let payment_amount = Math.random(); payment.textContent = 'You are going to pay: ' + payment_amount; });
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="selection-div"> <select id="bank-select" name="Bank"> <option value="BankId1">Bank1</option> <option value="BankId2">Bank2</option> <option value="BankId3">Bank3</option> </select> </div> <div> <p id="payment">You are going to pay: </p> <button id="calculate-button">Calculate</button> </div> </body> </html>

When a user selects an option from the dropdown, the "selected" attribute will automatically be added to the element in the DOM. From there, you'll need to have your code retrieve the user's selected option from the dropdown when calculating the payment like so...

First, get the dropdown options:

const bankOptions = document.getElementById('banks');

Second, set the 'selectedBank' variable to the user's selected option:

const selectedBank = bankOptions.value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM