-2

I have a form like so and I am trying to get the submit-button to show an alert but it doesn't seem to be doing anything and I have no errors in the console. I have all the required jQuery included as I have a similar form in another section of the page and the input submit works but this form doesn't seem to be.

<div id="div_1" style="display:none;">
            <form id="form1">

               <fieldset style="border:0;">
                  <div>
                        <label for="name">Name</label>
                        <input id="name" name="name" placeholder="First name" required type="text">
                    </div>
                    <div>
                        <input id="submit-button" type="submit" value="Submit">
                    </div>

                </fieldset>
            </form>

            <div>
                <button id="close" type="submit" value="Close">
            </div>
        </div>

js

$("#submit-button").click(function(){
    alert("boo");
});

1 Answers1

2

Make sure the javascript is ran after the element is in the doctree.

Use this instead of just your js:

$(document).ready(function())
{
    $("#submit-button").click(function(){
        alert("boo");
    });
}

This makes sure the DOM tree is loaded and then it'll bind the click event. If you bind the click event in a JS file, it could be loaded before the element is in the DOM tree, making the jQuery selector unable to find the element (thus the click event won't fire as it's not bound).

Joshua Bakker
  • 1,831
  • 2
  • 22
  • 52
  • Is the popup created dynamically? Because if you create a popup in javascript the click event won't be bound. – Joshua Bakker Oct 14 '15 at 14:17
  • I have two divs, so div 1 is displayed and div 2 is hidden, when I click submit in the first div its posts the data via ajax and replaces it with this code `$('#div').html($('#div_1').html());` – abcdefjk123 Oct 14 '15 at 14:22
  • But I have the close button in that div which has a click event and it works! – abcdefjk123 Oct 14 '15 at 14:23