I have a HTML code generated dynamically from a model using .NET MVC. Between the field there is a select with selected option (based on the data from the model).
<select class="myClass" data-val="true" id="sampleSelect" name="sampleSelect">
<option value="">Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
</select>
I want to attach change event using jQuery like this:
$('#sampleSelect').change(function () {
var test = $('#sampleSelect').val();
});
Or like this:
$('#sampleSelect').on('change', function () {
var test = $('#sampleSelect').val();
});
Or even with delegate... none of those works. It seems that there is no change done, option value 3 remains with selected attribute.
I don't want to modify the HTML, I just one to use the right javascript code to catch the event.
Do you have any suggestions?
Edit: Attribute selected remains on value 3. Even if I select different item. And the change event doesn't fire. I don't know why. This is my problem.
FINAL EDIT: My bad, the selecting was done in a right way. The problem is that there were 2 selects with the same id and jQuery kept choosing the hidden one somewhere else on the screen.
Thanks for the fast answers though.