Reputation: 329
I have a little script that copys whats in the drop down. But I want the drop to display the firstname and when the firstname is selected I want it to copy the lastname outside. I need to use an attribute other than VALUE
JS:
function copy() {
document.getElementById("label").innerHTML =
document.getElementById("mySelect").value
}
HTML:
<div id="label"></div>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="firstname" id="lastname">Firstname</option>
<option value="firstname" id="lastname">Firstname</option>
<option value="firstname" id="lastname">Firstname</option>
<option value="firstname" id="lastname">Firstname</option>
</select>
or see here http://jsfiddle.net/r6Fus/
Upvotes: 0
Views: 117
Reputation: 987
Add a data-surname
attribute to each <option>
:
<option value="tcs" data-surname="Washington" >tcs</option>
(You can do this with ID but data attribute seems a better solution in this case)
Then update your function to rerieve the surname attribute: (using jQuery is recommended)
function copy( {
$("#label").html($("#mySelect option:selected").data("surname"))
}
Working example (try the first option in the menu) - jsFiddle
Upvotes: 2
Reputation: 4065
You should't misuse an element's id
attribute just for the sake of providing an <option>
with additional data.
As suggested in another answer, you could instead specify an additional attribute like data-lastname
and later access that in your script (the following code is untested).
Your HTML could look like:
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="firstname" data-lastname="lastname">Firstname</option>
<option value="firstname" data-lastname="lastname">Firstname</option>
<option value="firstname" data-lastname="lastname">Firstname</option>
<option value="firstname" data-lastname="lastname">Firstname</option>
</select>
Your JS function could look like:
function copy() {
var sel = document.getElementById('mySelect');
var selected = sel.options[sel.selectedIndex];
var firstname = selected.value;
var lastname = selected.getAttribute('data-lastname');
// do stuff...
}
Upvotes: 3