0

I have a $(document).ready(function() function on this page which fires successfully (so my javascript is loading successfully).

I am trying to fire an event when my select box is changed, but cannot get it to fire at all (even when I make it a click event). This is in Django Admin, so I cannot easily add an id to the element (I'm sure it's not that difficult but I can't find how).

This is the element I'm trying to listen for:

<select name="base_module" required="" id="id_base_module">

These are a few things I've tried:

var test = document.querySelector('[name="base_module"]');
$(test).click(function(){
    console.log("success")
});

$('#id_base_module').click(function(){
    console.log("success")
});

$('select#id_base_module').change(function(){
    console.log("success")
});

I've added my javascript file in my Django Admin page with this code under the correct model in the associated admin.py file:

class Media:
        js = (
            'js/javascript.js',
        )

Any help setting an event listener on this element which will be fired when the item in the select box is changed would be appreciated.

Thank you.

horse
  • 479
  • 7
  • 25

2 Answers2

1

Turns out I had to use the following:

$(document).on('change', '#id_base_module', function(event) {

Due to 'dynamically created content'.

Thanks trincont's answer in this post.

horse
  • 479
  • 7
  • 25
0

You want to use the change event for sure, not the click event.

This:

$('#id_base_module').change(function(){
    console.log("success")
});

Worked for me (not much of a change from what you had already in your third approach). Your first approach will work as well, just change it to use the change event instead of click.

redouglas
  • 210
  • 1
  • 5
  • Thank you, I actually tried that already as it seems like the correct thing to do. I just tried it again and it didn't work. I guess something else may be the problem then, though I'm not sure what, I though it's possible that the link to the javascript cdn wasn't being inserted properly, though my ```$(document).ready(function()``` function is working, so that can't be it (unless a ready function doesn't need the javascript cdn to work). Thanks for your input, I'll keep trying :) – horse Jul 07 '20 at 00:53
  • Are there any console errors? Also might be worth trying to `console.log` your `test ` variable to make sure it's selecting something. This won't work if the ` – redouglas Jul 07 '20 at 00:59
  • I can console log my ```test``` variable successfully, and I don't get any errors, though I do get a message ```A cookie associated with a cross-site resource at http://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver...``` which I'm actually happy with because it tells me the javascript cdn is working – horse Jul 07 '20 at 01:02