简体   繁体   中英

I'm trying to get Textarea value from a dynamically generated form but when I click the button nothing happens

I have a HTML document completely generated from jQuery, and in that I have a form. I am trying to get the value entered inside the text area when I click on the button but it stays 'undefined'.

My HTML in jQuery:

jQuery('<form/>', {
    id: 'username_form',
    "class": 'username_form'
    }).appendTo('#header');

    jQuery('<h2/>', {
    text: 'Please enter a Username',
    id: 'popuptitle',
    "class": 'username_title'
    }).appendTo('#username_form');

    jQuery('<textarea rows="1" col"50"/>', {
    id: 'username_text',
    "class": 'username_form'
    }).appendTo('#username_form');
    /*      btn submit   */ 
    var btn_submit= document.createElement('input');
    btn_submit.setAttribute('id','btn_Submit');
    btn_submit.setAttribute('type','button');
    btn_submit.setAttribute('name','btn_Submit');
    btn_submit.setAttribute('value','Submit');
    $(btn_submit).appendTo('#username_form');

My function:

    $('#btn_Submit').click(function() {
        //alert("Submitted");
        var username = $.trim($("#username_text").val());
        alert($("textarea#username_text").text());

        if(username != ""){
                // Show alert dialog if value is not blank
                alert(username);
            }
    });

The only thing happening in my alert is a blank or 'undefined'

When you create dynamic element, jQuery don't know about this element at starting time and cannot attach event to it. You button element cannot bind event.

You have to bind your event to existing parent element like so:

$(document).on("click",'#btn_Submit',function() {
...
});

I think it's a problem related to jQuery's function jQuery when you try to create a textarea. It doesn't get the informed id . If you use only this way:

jQuery('<textarea/>', {

It works. (but you also need to use .val() instead of .text() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM