-4

I insert a text box into my page with jQuery .html("<input type="text>")

Once I click a button, I loop through ($("input[type=text]).each) and then need to get the value of each text box. When I try to get that val() of that text box it returns empty string, although I have typed something in there

console.log($(v).val()) = "empty string"

EDIT

$("input[type=text]").each(function(k, v) {
                console.log($(v).val());
            });
Harry
  • 13,091
  • 29
  • 107
  • 167

3 Answers3

2

If you are appending to the DOM you should look into using jQuerys live method:

http://api.jquery.com/live/

marto
  • 4,402
  • 25
  • 15
  • I am using live with all my events – Harry Jul 29 '11 at 10:41
  • @Harry you're adding elements after the document is loaded, your .each won't work, .live will. See the .live docs I linked to – marto Jul 29 '11 at 10:46
  • @marto have you read the question? He iterates over inputs *on button click*. It's not that the click handler never executes, it's that values are empty. – katspaugh Jul 29 '11 at 10:51
  • @katspaugh that part must have been added when they edited their post. – marto Jul 29 '11 at 10:53
1

TRY

 $('#myForm').live('click', function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

either use serializeArray

 $('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • I suspect for the same reason I got downvoted and called out by katspaugh. The quesiton has been edited several times since it's inital post, wasting everyones time – marto Jul 29 '11 at 10:57
  • The inputs selector is wrong, by the way. Should be `$('#myForm input');`. – katspaugh Jul 29 '11 at 11:04
  • @katspaugh; have u seen the line under that function??? – xkeshav Jul 29 '11 at 11:05
  • Actually, there *is* `:input` selector (http://api.jquery.com/input-selector/). Mea culpa. – katspaugh Jul 29 '11 at 11:15
  • @katspaugh would you like to tell me what is the difference between those?? – xkeshav Jul 29 '11 at 11:51
  • `input` is a standard tag-name selector (see http://www.w3.org/TR/selectors-api/); `:input` is jQuery's own selector that matches all form elements: actual input elements, buttons and textareas. – katspaugh Jul 29 '11 at 13:25
-1

Sorry for this, I actually see now that me problem was from something ells in my app and not what I was thinking it is. Sorry for wasting time

Harry
  • 13,091
  • 29
  • 107
  • 167