user2026937
user2026937

Reputation: 1

pass id to function when select option is changed

I have a select list. When an option is selected I need to pass it's value and id to a javascript function:

<select name="cardType" id="cardType" onchange="addSurcharge(this.value, this.id)">
  <option value="2" id="debitcard">Mastercard Debit Card</option>
  <option value="2" id="creditcard">Mastercard Credit Card</option>
</select>

a mastercard must have a value of 2, but I need to differentiate between credit and debit cards.

The addSurcharge() function will add a transaction fee to credit cards e.g. if value == 2 && cardID == "creditcard" add the surcharge.

the onchange event will send the select id "cardType" in above example.

how do i get it to send the selected option's id?

ideally without jquery as i don't use it for anything else and would rather avoid adding it just for this purpose.

Upvotes: 0

Views: 2547

Answers (2)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114447

Just pass "this".

Unlike textboxes, you can't just grab .value from a select. You need to grab the value based on the selected index.

addSurcharge(this)

function addSurcharge(sel) {
    val = sel[sel.selectedIndex].value
}

Upvotes: 1

hank
hank

Reputation: 3768

this.options[this.selectedIndex] will refer to the selected option, from that you can get .id or .value.

Upvotes: 1

Related Questions