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/

2 Answers 2

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.

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

Comments

0

Uninitialized var output actually has a value undefined.

var output; // Value of output is undefined
output += "2"; // undefined + "2" ->  "undefined2"

Comments

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.