2

I want to use Vanilla JS instead of the below jQuery code to get the attribute value of the selection.

$("#PartnerTypeID").find(':selected').attr('data-id');

How is this possible?

document.getElementById("PartnerTypeID").addEventListener("change", function() {
  console.log(this.getAttribute("data-id"))
});
<select id="PartnerTypeID" name="PartnerTypeID" placeholder="Select...">
  <option value="">Select...</option>
  <option data-id="hospitals" value="1">Hospital</option>
  <option data-id="daycare" value="2">Daycare</option>
</select>

2 Answers 2

3

You're setting an event listener on the select, which means that this refers to that select element itself. Which doesn't have the attribute you're looking for, instead you need to get the option element that was selected and extract the attribute from there instead.

document.getElementById("PartnerTypeID").addEventListener("change", function() {
  console.log(this.options[this.selectedIndex].getAttribute("data-id"));
});
<select id="PartnerTypeID" name="PartnerTypeID" placeholder="Select...">
  <option value="">Select...</option>
  <option data-id="hospitals" value="1">Hospital</option>
  <option data-id="daycare" value="2">Daycare</option>
</select>

The .options property gives you back all the options for the select element, and the .selectedIndex property gives you the index of the option currently selected.

Sign up to request clarification or add additional context in comments.

Comments

0

PartnerTypeID.onchange = function(){
console.log(this[this.selectedIndex].getAttribute('data-id')) 
}
<select id="PartnerTypeID" placeholder="Select...">
  <option value="">Select...</option>
  <option data-id="hospitals" value="1">Hospital</option>
  <option data-id="daycare" value="2">Daycare</option>
</select>

This used to work with this[ this.selectedIndex ].attribute[ 'data-id' ], but for some highly ignorant reason - it no longer does!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.