简体   繁体   中英

How do I get click event of model form button?

On my django web app, I have a webpage and when a button is clicked a modal form is opened. On this form there are a few fields and a save button. When the save button is pressed, I want to do something, like printing an alert. Here is what I tried:

Model form code:

<div class="container-content">
    <div class="infor-experience col-lg-2 more_info">
    {% if request.user|isEmployer %}
        <div class="add-to-list">{% include "layout/addtolistmodal.html" %}</div>
        <div class="connect-now bottom">{% include "layout/bidmodal.html" %}</div>
    {% endif %}
 <!-- more code below here -->

Javascript block in same HTML file as modal above:

<script type="text/javascript">
    // Add to short list handler
    $('.add-to-list').on('click', '.submit', function(e) {
        alert("TEST");
    })
</script>

Basically, what I want to do is when the user clicks save on the add-to-list modal, print the alert "TEST".

From my understanding the reason its not working is because it cannot find '.add-to-list' but what I should use instead?

Just attach your click event to already present element which seems to be div.infor-experience , since your modal html gets appended after DOM load . Also, make sure your script renders in web browser if you have provided any conditions for them to render.

$('.infor-experience').on('click', '.submit', function(e) {
        alert("TEST");
})

It might be that positioning of your script. At the time of its execution the DOM may not be ready or exist yet.

You could wrap your DOM related codes like so:

$(document).ready(init);

function init(){ 
  $('.add-to-list').on('click', '.submit', function(e) {
    alert("TEST");
  })
}

Try this instead

$(document).ready(function () {
    $('.add-to-list').on('click', '.submit', function(e) {
        alert("TEST");
    });
});

you should add the code under $(document).ready() so that it waits for whole DOM to load and then attaches the method instead doing so before loading of DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM