1

I am trying to add more than one attr() value when using append in a dropdown in jQuery.

This is working fine:

$('#twostages').append($('<option/>').attr("value", option.stage).text(option.stage));

And I can access the value using:

document.getElementById("twostages").value

However, when I try this code:

$('#twostages').append($('<option/>').attr({ "value": option.stage, "matone": option.matone }).text(option.stage));

I am not able to retrieve the value or matone using the document.getElementById("twostages").value or document.getElementById("twostages").matone

I got the idea of the above code from this topic: jQuery: Adding two attributes via the .attr(); method

Any help would be greatly appreciated.

Thanks.

Hamza Ahmad
  • 512
  • 2
  • 7
  • 32

1 Answers1

2

matone is a property added on options.So you can't access it directly.

you need to check first the selected option and then get it's corresponding matone value using .attr()

Working snippet:-

$('#twostages').append($('<option/>').attr({ "value":"stage1", "matone": "mymetion" }).text("stage1"));

console.log($('#twostages').val());
console.log($('#twostages').find(':selected').attr('matone'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="twostages">

</select>

Reference:-

.attr()

:selected

Note:- Standered practice is to use data-attributes for custom attributes

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98