SimpleProgrammer
SimpleProgrammer

Reputation: 321

jQuery added form elements cannot be selected

I apologise for the description if it's not fitting. It was hard to describe what's going on.

I have set up a jsFiddle here.

function addNewForm() {
    $('body').html(function () { //display log in form
        return "<input type=\"text\" placeholder=\"Word or Phrase\" id=\"prompt\" />\n" +
            "<textarea id=\"answer\" placeholder=\"Answer text\"></textarea>\n" +
            "<input type=\"button\" id=\"addnew\" value=\"Add This!\" />\n" +
            "<p>&nbsp;</p>";
    });
}

$("#addnew").click(function () {
    $("p").html("ADD NEW CLICKED<br />");
});

$("a").click(function () {
    addNewForm();
});

Is my syntax correct? For some reason, $("#addnew").click works when generated outside of its own function but the button stops working since I have tidied my code and placed it within its own function. Is there a reason that jQuery may not recognise an element that has been created through a function?

Cheers!

Upvotes: 3

Views: 93

Answers (2)

gre_gor
gre_gor

Reputation: 6787

When you are trying to attach an onclick event handler onto #addnew, the element doesn't exist at that time.
You need to attach it when you add the form into DOM or use delegated events

$(document).on("click", "#addnew", function () {
    $("p").html("ADD NEW CLICKED<br />");
});

You would probably also like to prevent the page from reloading, when you click the <a> link

$("a").click(function (e) {
    e.preventDefault();
    addNewForm();
});

Fixed jsfiddle: https://jsfiddle.net/5rb6koog/

Upvotes: 2

Halvra
Halvra

Reputation: 295

The solution is here :

https://jsfiddle.net/wvepd6ge/7/

When you add your button, you need to attach the event like this :

function addNewClicked() {
    $('.result').html("ADD NEW CLICKED<br/>");
}

$("a").click(function () {
    addNewForm();
    $("#addnew").click(function () {
        addNewClicked();
    });
});

Upvotes: 1

Related Questions