Search code examples
javascripthtmljqueryattributesattr

How to pass an attribute instead of the selected value in a dropdown


I would like to pass the email attribute in the testEmail variable but it is passing the name John Doe

<option value="2" email="[email protected]">John Doe</option>
var testEmail = $("#nameofDropdown option:selected").text();
var email = promt("Enter an email to send to", testEmail );

I know it has to do with this line option:selected just not sure what to change it to to get the email.


Solution

  • Use .attr() rather than .text()

    $("#nameofDropdown option:selected").attr('email')
    

    console.log($("option").attr('email'));
    <option value="2" email="[email protected]">John Doe</option>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>