N.Cre
N.Cre

Reputation: 167

How to store multiple drop down values inside a variable?

So I have this javascript function that loops through each user account and displays them in a drop-down menu. When the user selects an option from the drop-down menu, it takes the Iban number as its main id which is stored in ddlAccountFrom. Is there a way how I can store two values when the user selects an option, like for instance the Iban and Currency into separate variables?

function getAccountFrom() {
    var username = $("#hiddenUsername").val();

    var url = "http://localhost:63723/api/BankAccountsApi/GetBankAccounts/?username=" + username + "&id=2";
    $.getJSON(url, function (data) {
            var table = "<select id=\"ddlAccountFrom\">";

            table += "<option value=\"-1\">Select an Account</option>";
            $.each(data, function (key, val) {

                table += "<option value=\"" + val.Iban + "\">" + val.Iban + " | " + val.Currency + " | " + val.Balance + "</option>";

            });
            table += "</select>";
            $('#divAccountFrom').html(table);
    });
}

I am using the ddlAccountFrom in this function..

function Transfer() {
    var accountFrom = $("#ddlAccountFrom").val();
    var accountTo = $("#txtAccountTo").val();
    var amount = $("#txtAmount").val();


    var url = "http://localhost:63723/api/BankAccountsApi/TransferFunds/?  
    ibanFrom=" + accountFrom + "&ibanTo=" + accountTo + "&amount=" + amount;

    $.getJSON(url, function (data) {
        alert(data);
    })

    .error (function () {
        alert("Not enough balance! The amount entered exceed the balance found in this account. Please try again.");
    })

}

Upvotes: 1

Views: 785

Answers (2)

lamp76
lamp76

Reputation: 333

You can use the data-custom attribute, like this:

table += "<option value=\"" + val.Iban + "\" data-currency=\"" + val.Currency + "\">" + val.Iban + " | " + val.Currency + " | " + val.Balance + "</option>";

To access variable see jquery-cant-get-data-attribute-value So you can read:

var selectedCurrency= $("#ddlAccountFrom :selected").data('currency');

Upvotes: 2

soywod
soywod

Reputation: 4520

You could :

  1. Concatenate your 2 data in 1 string with a separator (for ex myIban#myCurrency) and then split your value to get back your 2 distinct data
  2. Listen to your dropdown changes, for example adding a onchange=updateData(val.Iban, val.Currency) attribute to your option html, and in your js :

    var currentIban, currentCurrency;
    
    function updateData(iban, currency) {
        currentIban = iban;
        currentCurrency = currency;
    }
    
  3. Add a data-custom attribute, like data-currency or data-iban

Upvotes: 0

Related Questions