Reputation: 1605
I think this will be a really easy one for anyone that is decent with jQuery, but I've got dynamically generated dropdownlists on my page, and I've set up a click event on the class, which, as expected fires a click event for all of them. The ID of the select
is dynamically generated, so I can't use that as the selector. I just want to fire the event for the select
that is actually changed.
I need to use the id of the selected value in the function - anyone know how this is done?
Code I have so far:
$(document).ready(function () {
$(".boxItem").change(function () {
var str = $(this).attr('id');
var num = $(this).val();
alert(num);
var url = "/Search/GetBoxChangeInfo";
var vmData = { json : @Html.Raw(Json.Encode(Model)),
id : str,
boxNo : num };
$.post(url, vmData, function (data) {
$("#column-1").html(data);
});
});
});
Many thanks
Upvotes: 3
Views: 13438
Reputation: 87073
$(".boxItem").on("change", function () {
// to get the value and id of selected option
var str = $('option:selected', this).attr('id');
var value = $('option:selected', this).attr('value');
// or to get value and id of select box use
var str = this.id;
var value = this.value;
......
});
If you select
is live i.e created after DOM ready then you should try
$("body").on("change", ".boxItem", function () {
// to get the value and id of selected option
var str = $('option:selected', this).attr('id');
var value = $('option:selected', this).attr('value');
// or to get value and id of select box use
var str = this.id;
var value = this.value;
......
});
Upvotes: 1
Reputation: 318192
If it's dynamic you'll need to delegate:
$(document).on('change', '.boxItem', function () {
var str = this.id;
var num = this.value;
......
this
will refer to the select with the class .boxitem
that was changed, and getting the ID and value should work as expected, also replace document with closest non dynamic parent!
Upvotes: 2