horse
horse

Reputation: 501

Can't Get Event To Fire On Select Box Change

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.

Upvotes: 0

Views: 391

Answers (2)

horse
horse

Reputation: 501

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.

Upvotes: 1

redouglas
redouglas

Reputation: 208

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.

Upvotes: 0

Related Questions