0

I'm writing a code for a simple forum, topics are listed and there is a possibility to add a new topic on the fly by clicking a link (image) in which a form will be added into an empty div (via .html()), how can i catch form submitting event from this particular form?

code below:

<li class="cat_root_li">New Subject<br />
  <span class="disc_span">Some EExplanation</span>
  <ul>
    <li>No Topics currently
    </li>
    <li id="3">Add a new topic <a href="#" class='new_topic_li' checked_link="0"><img src="images/list-add-2.png" height="28px" style='position:absolute;margin-top:-2px;' /></a>
      <div id="new_topic_div"></div>
    </li>
    <li style="list-style: none">
      <br />
    </li>
  </ul>
</li>

my Script is the following:

<script>
    $(document).ready(function(){
        $('div#new_topic_div').hide();
        var form = "<form id=add_new_topic_form action='' method=POST>\n <table class=add_new_topic_form_table border=0>\n <tr><td colspan=2><?=tjcg_add_topic;?></td></tr><tr><td valign=top><?=tjcg_form_post_title;?></td><td valign=top><input type=text name=new_topic_title id=new_topic_title><td></tr>\n <tr><td valign=top><?=tjcg_form_post_subject;?></td><td valign=top><textarea name=new_topic_text id=new_topic_text class=widgEditor rows='5' cols='45'></textarea></td></tr><tr><td class=add_topic_result></td><td><input type=submit class=submit_btn value='<?=tjcg_form_submit;?>' /> <a class=test_href href=#>link</a></td></tr>\n <table>\n </form>";
        $('a.new_topic_li').on("click",function(e){
        e.preventDefault();
        var parent= $(this).closest('li')
        var checked = $(this).attr('checked_link');
        if (checked == 0)
        {
        parent.find('div#new_topic_div').html(form).show(200);
        $(this).attr('checked_link',"1");
        }
        else{
        parent.find('div#new_topic_div').html('').hide(200);
        $(this).attr('checked_link',"0");
        }
        });
    });
</script>

is there a way to catch form submit event from this code?

Tarek Sawah
  • 305
  • 4
  • 12

2 Answers2

2

Yes, using on()

$(document).on('submit', '#add_new_topic_form', function(){
  alert("I've been submitted");
});

You can replace document in $(document) by the closest parent of the form.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
0

As its dynamically created you'll have to do something like this :

 $('div#new_topic_div').on('submit', 'form#add_new_topic_form', function() {
      console.log('submitting');
 });
JF it
  • 2,403
  • 3
  • 20
  • 30