2

I'm working on going through all values in a form but I keep getting undefnined then my values show up. I'm dynamically creating the form so I think the undefined maybe coming from the blank field.

Here's the code I'm using to get all the elements:

//try to get all elements
var output;
$(this).parents('form') // For each element, pick the ancestor that's a form tag.
.find(':input') // Find all the input elements under those.
.each(function(i) {
    //alert(this.value+ " = " + i);
    if (typeof this.value === "undefined") {
        output = "nothing here";
    } else {
        output += this.value;
    }
});
$("div#total").append("value = " + output + "<br>");

If I enter 1,2,3,4,5,6 then my output is:

hello value = undefined
value = undefined1
value = undefined1
value = undefined12
value = undefined12
value = undefined123
value = undefined123
value = undefined1234
value = undefined1234
value = undefined12345
value = undefined12345
value = undefined123456

The result is what I want except for the undefined part. I saw this answer: JavaScript: undefined !== undefined? and have tried their suggestions but I can't seem to get my program to save the value if the value is NOT undefined.

If it helps here's the full code: http://jsfiddle.net/lostsoul/rKLrZ/

Community
  • 1
  • 1
Lostsoul
  • 25,013
  • 48
  • 144
  • 239

2 Answers2

3

Initialize output to an empty string.

var output = "";

If an input has no value, it'll give you an empty string instead of undefined.

0

Uninitialized var output actually has a value undefined.

var output; // Value of output is undefined
output += "2"; // undefined + "2" ->  "undefined2"
xiaowl
  • 5,177
  • 3
  • 27
  • 28