Mike
Mike

Reputation: 6839

Dynamically inserted form and Jquery submit

I have a form that I insert dynamically. When a link is clicked I execute this jQuery:

var newhtml = ' <div class="nav-wrapper"> <form id="target"> <div class="input-field"><input id="search" type="search" required> <label for="search"><i class="material-icons">search</i></label><i class="material-icons">close</i></div></form></div> ';

        //replace nav bar with search bar
        $("#replaceBar").replaceWith(newhtml);

I also have this in my javascript file:

$("#target").submit(function (event) {
        alert("search submitted");

    });

My issue is that I think the jquery for the submit is not being attached since the form is being submitted after the JS loads.

I eventually want the form to go to a new html page with the data that was in the form.

Upvotes: 1

Views: 107

Answers (4)

Mike
Mike

Reputation: 6839

My codes was correct I just had the on submit event binded in a different function. I needed it to be right after the insert.

Now it works perfectly.

Upvotes: 1

user2575725
user2575725

Reputation:

Try the event handler with document:

$(function(){
  $(document).on('submit',function(e) {
    e.stopPropagation();
    if('target' === e.target.id) {
      //to do here
    }
  });
});

Upvotes: 0

attackOnFC
attackOnFC

Reputation: 1

dynamically inserted elements need to use $().on(); if you don't know what is, search it in Jquery API. your submit event bind before the event-target elements id inserted, then the script can't work as you expected.

Upvotes: 0

benjarwar
benjarwar

Reputation: 1804

I think the issue is you don't have a submit button. Using your demo code, if I hit enter from the input field, I see the alert.

Try this:

$(document).ready(function() {
  var newhtml = '<div class="nav-wrapper"> <form id="target"> <div class="input-field"><input id="search" type="search" required><input type="submit" value="search"></div></form></div>';

  //replace nav bar with search bar
  $("#replaceBar").replaceWith(newhtml);

  $("#target").on('submit', function (event) {
    alert("search submitted");
  });
});

Upvotes: 1

Related Questions