0

I have a select element that I am adding options to dynamically using data from a variable called 'results':

HTML:

<select id="categories">
    <option selected disabled>Select your category</option>
</select>

jQuery:

$.each(results.Subcategories, function(index,category) {
    var category = '<option value="'+category.Name+'" data-index="'+index+'">'+category.Name+'</option>';
    $('#categories').append(category);
});

This works correctly and I am able to choose between the dynamically added options in the select element.

What I need to do now is get the 'value' attribute of the currently selected AFTER the user has chosen it from the added options. This is where I am getting stuck. I thought that something like this would work:

$('#categories').on('change', function() {
    var optionSelected = $("#categories option:selected", this);
    console.log($(optionSelected).data("value"))
});

But the selected attribute does not move on the options when I choose a new one, so I am unable to target that attribute to get the value.

Assuming the approach above is solid, how do I get my newly selected option to have the selected attribute so I can target it and get the value? Or is there a better approach that I'm missing? Thanks in advance.

7
  • just do $(this).val() or this.value to get the selected value. Commented Feb 11, 2016 at 23:55
  • @DinoMyte - but how do I know what 'this' is for the newly selected option, without the 'selected' attribute? Commented Feb 12, 2016 at 0:18
  • 2
    'selected' attribute specifies which option should be pre-selected in the select element when it is loaded. are you trying to insert the option from external event and have it displayed selected in the select element ? Commented Feb 12, 2016 at 0:20
  • I see, I think I misunderstood the selected attribute. All I really need to get is the value of the currently selected option after any change. Commented Feb 12, 2016 at 0:23
  • 1
    In that case, just do $(this).val() or this.value to get the current selected value. Commented Feb 12, 2016 at 0:25

1 Answer 1

1

Selected attribute will select an option from load. What you need is this.val() or you could use plain javascript and use getElementById(id of your option element).value() and get the value that way.

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

3 Comments

Thanks, yes I was misunderstanding the use of the selected attr. Your solution is correct.
It's this.value, not this.val()
You can use both. In jQuery it is $(this).val() and when using pure JavaScript you can use .value() His question tags jQuery. I just gave him the option of using either.

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.