2

I have a form dynamically created using Jquery and i am trying to validate the form but every time i try to get the input field value it says "undefined" , My code to get value

var username = $('#username').val();
       console.log(username);

Edited : Below function will add the form field to the div.modal

    function AddUserDialog(){
      var temp = '<input type="text" name="username" id="username" />';
       $('.modal').html(temp);
     }

Thanks

9
  • can you post the form that is dynamically created Commented Mar 2, 2012 at 2:48
  • We are going to need more information. Your question is the equivalent of "I'm trying to drive my car, but every time I try to drive it, it has problems." How is the form being created? Have you made sure it's in the DOM when you're searching for it with jQuery? Have you made sure its id is properly 'username'... so on. Commented Mar 2, 2012 at 2:49
  • @corbin :- yes form is in the dom and id is also correct.. Commented Mar 2, 2012 at 2:53
  • does that input element gets appended to DOM. Check it in firebug or chrome dev tools. Commented Mar 2, 2012 at 2:53
  • The code to pull the username value must be getting run before the code that is inserting the element into the DOM then. What triggers the validation event? Commented Mar 2, 2012 at 2:54

1 Answer 1

4
$("#form_id").live('submit',function(){
    if($(this).find('#username').val()==''){
        alert('username cant left empty!!');
        return false;
    }
});

Because the form is created by jquery your script can't find it in document and will return undefined.. For such cases we have 3 functions we can use..live,delegate and on..

Read following links for more details..

Live
delegate
on

Sign up to request clarification or add additional context in comments.

1 Comment

live and delegate are deprecated, just for what it may be worth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.