I have a simple form that has a list (dropdown list generated from a DB), when a user makes a selection, the selection is printed on the screen. The problem I'm having is that if I use jquery to call the php funciton that generates the list when the page is loading, the list will not work, but if I add the code directly in the html it will work
When the page loads the dropdown list is called like this:
$('#createDropDown').ready(function(){
id = $('#createDropDown').val();
// this calls a php function that creates a dropdown list from the DB
// the dropdown's id = 'categoryList'
xajax_addDropdownMenu(id);
});
the list is generated with the id = 'categoryList', and it is appended correctly to the createDropDown DIV called "createDropDown". Up until now everything looks good! The problem comes when a selection is made on the newly created list (categoryList) another Jquery is called
when a selection is made the following code should be called:
$('#categoryList').change(function() {
bucket_id = $('#categoryList').val();
var selected = "";
// get selected value from the dropdown menu
$("#categoryList option:selected").each(function () {
selected += $(this).text() + " ===>";
});
// if we have a valid ID print it in the screen.
if(bucket_id!= 0)
{
xajax_addCategory(selected);
}
});
xajax_addCategory(selected); prints the selected item on the screen. but is not working.
NOTE: This works OK if I call the php function to generate the dropdown directly in the main.html file, so I know that the list is being generated with the correct ID and it works, but when I use Jquery to call the php method on load, it doesn't work... and I don't understand why.
PS I'm a noob of Jquery so some insight would be very welcome!
UPDATE:
I tried creating a binding after the list is generated like this:
$('#createDropDown').ready(function()
{
id = $('#createDropDown').val();
xajax_addDropdownMenu(id);
$("#categoryList0").bind('change',function()
{
console.log('The code goes here!!');
});
});
where categoryList0 is the ID of the new list. the class of the list is categoryList
but I'm still stuck because it is still not getting into the function when there is a change...
Your second code snippet finds all elements that match #categoryList and binds a function to the change event. The problem is that there is no #categoryList element at that time, since you create it later on. Thus you need to do the binding after the list has been created.