Ad

JQuery: Accessing (multi) .attr()

- 1 answer

I have a problem accessing the information of a (multi) .attr(...) I found this and tried to adapt it - but it does not work. I am missing something obvious here (new to js). Hope to find help here!

var user_id = document.getElementById('myselect').options[select.selectedIndex].user_id;
var user_email = document.getElementById('myselect').options[select.selectedIndex].user_email;

document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;
<select id="myselect">
  <option user_email="[email protected]" user_id=1>Test 0</option>
  <option user_email="[email protected]" user_id=1>Test 1</option>
  <option user_email="[email protected]" user_id=1>Test 3</option>
</select>

<div id="display"></div>

Ad

Answer

select.selectedIndex doesn't exist in your example. This should work:

var select = document.getElementById('myselect');

var user_id = select.options[select.selectedIndex].getAttribute('user_id');
var user_email = select.options[select.selectedIndex].getAttribute('user_email');

document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;
Ad
source: stackoverflow.com
Ad