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.

1
  • matone is not a default property and hens you can not access directly. You can use jquery .attr() in same way to get value Commented Nov 5, 2018 at 7:02

1 Answer 1

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

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

1 Comment

@HamzaAhmad glad to help you

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.