hjb-web design hjb-web design - 1 year ago 57
jQuery Question

adding search bar through JavaScript

I have a working search bar that is added through the html. However to make the code unobtrusive i am trying to append the search bar and button through JavaScript. I am able to display the search bar and button, but the functionality of bringing up results has stopped working.

Here is the section to add the search bar in JS.

var $searchSection = $('<div class="student-search"></div>');
$searchSection.append('<input id = "search-criteria" placeholder="Search for students..."></input>');

//Append search section

I am trying to get the functionality of search working. Here is a link to the code with the search working, as the search bar is included in the html. http://codepen.io/fun/pen/RRyaNm

This is a link to the code with search bar added through the js but with no search functionality. http://codepen.io/fun/pen/VjraNd?editors=1010

How do you get the search to work through adding from the js?

Any help or pointers would be awesome.

Thank you,


Answer Source

As Siguza said, $('#search-criteria') doesn't exist at the time you're fetching it. So, the on function is a good idea, but it should be given like this :

$('.page-header').on('input', '#search-criteria', function() {
     //your code

What it does is , it will bind the function to the element that is added dynamically in DOM

Here is the jsFiidle

It will work for you. :)