0

I have a list of files on a server displayed on a page. I also have a button to create a folder. Clicking the button generates a new text input where a name for the folder can be entered, which is nested in an html form. I then want to write some ajax there however the .submit function of Jquery doesn't see the newly generated text input field, therefore I cannot get this to work. Here's my jquery:

$(document).ready(function(){
var csrf = "{% csrf_token %}";
var fields = 0;
$('#newFolder').click(function(){
  var folderName = $('<form method="post" class="createFolder">' + csrf + '<li><input type="checkbox" class="styled-checkbox"><div id="name"><input type="text" id="fieldName" /></div></li></form>');
  $('.objectsList').append(folderName);
  });
$('.createFolder').on('submit', function(event){
  event.preventDefault();
  alert("fieldName");
  });
});

So when you click on #newFolder a new li with a form is generated. I enter the name for the folder and as I click enter I get redirected to the same page but blank. If I hardcode this form with text input it works fine. I understand that Jquery loads along with the page and if something is generated after the page has loaded then it will not see it, correct? How can I make it 'see' this newly generated form and its fields?

Thanks

davidb
  • 1,087
  • 2
  • 16
  • 37
  • Your case isn't json, but the dynamic content issue is the same. – Taplar Dec 05 '17 at 21:23
  • you should add wrapper element and have the form(s) appended to it. https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – flynorc Dec 05 '17 at 21:23
  • @flynorc or they could just use a delegate event binding... – Taplar Dec 05 '17 at 21:24
  • @Taplar is delegate event binding not the same principle that the answer of the question that I linked uses? Where you define an event listener on the parent element (that already exists) and then use the on("click", "selector", function) ? like here: https://learn.jquery.com/events/event-delegation/ – flynorc Dec 05 '17 at 21:29
  • It is, now that I read your link, however your lead in text didn't express that. It simply said add a wrapper element. It didn't say why. Edit: also your link would be another possibility for a close vote due to question duplication. – Taplar Dec 05 '17 at 21:32
  • Is my understanding correct? I need to hardcode a form and dynamically create an element which I need to call via the submit function in Jquery? – davidb Dec 05 '17 at 21:41
  • Alright, I already got it working. Thanks guys! – davidb Dec 05 '17 at 21:44

0 Answers0