Bing
Bing

Reputation: 3171

Javascript: Passing data via an option element and "onchange"

I have a "select" element which is being populated by a PHP file. The output is a list of locations with names, addresses, cities, states, etc. I'd like to make it so when this dropdown is changed the new address is loaded into the address form.

Here is the code I'd like to get working, which might explain this better:

<select name='address' id='address'>
    <option value='0' onselect='clearAddress()'></option>
    <option value='1' onselect='loadAddress("1 Main St", "New York")'>Mark's House</option>
    <option value='2' onselect='loadAddress("5 Arc Rd", "Orlando")'>Bob's Apt</option>
    <option value='3' onselect='loadAddress("2 Fox Ln", "Clinton")'>Joe's Bar</option>
</select>

I know onselect doesn't work here, and while adding "onchange" to the select element might work, I can't see how it would function for individual options.

Any thoughts on how to do this? Thanks!

Upvotes: 1

Views: 590

Answers (1)

Mithun Satheesh
Mithun Satheesh

Reputation: 27835

May not be a proper solution but you can do it via

<select name='address' id='address' onchange="doCall(this)">
    <option value='0' data-load=''></option>
    <option value='1' data-load='1 Main St,New York'>Mark's House</option>
    <option value='2' data-load='5 Arc Rd,Orlando'>Bob's Apt</option>
    <option value='3' data-load='2 Fox Ln,Clinton'>Joe's Bar</option>
</select>

and

function doCall(elt) {

   var params = elt.options[elt.selectedIndex].getAttribute("data-load").split(",");

   alert(params[0]);
   alert(params[1]); 

}

here is a fiddle.

Upvotes: 2

Related Questions