I am using JS & FormData to gather values from an html form and then create string which is saved in localStorage. But I am getting "undefined" prepended to the first value.
My form:
<form id="prd2">
<input type="hidden" name="product" value="et345">
<input type="hidden" name="name" value="Tshirt">
<select name="quantity"><option value="1">1</option><option value="2">2</option><option>etc</option></select><br>
<input type="hidden" name="img" value="img345">
<input type="hidden" name="optType" value="clothing">
<button id="btn2" class="addcart">Add to Cart</button>
</form>
My JS for grabbing the values:
var additem;
var frm = document.getElementById('prd2');
var data = new FormData(frm);
for (var value of data.values()) {
additem += value + '|';
}
I also tried setting var additem = '';
I am expecting the value of additem to be:
et345|Tshirt|2|img345|clothing|
But I am ending up with:
undefinedet345|Tshirt|2|img345|clothing|
While I can manually remove the "undefined" from the string before storing, I would prefer to find out why it is being appended to begin with.
Assigning the zero-length string will solve this.
Do this:
var additem = "";
Instead of this:
var additem;
Because Javascript naturally assigns the value undefined
to every variables, so when you add it with another string, it will just append the undefined.
For example:
var shouldBeUndefined;
var shouldBeNullString = "";
console.log(shouldBeUndefined);
console.log(shouldBeNullString);
shouldBeUndefined += "concat";
shouldBeNullString += "concat";
console.log(shouldBeUndefined);
console.log(shouldBeNullString);
Full working code:
var additem = "";
var frm = document.getElementById('prd2');
var data = new FormData(frm);
for (var value of data.values()) {
additem += value + '|';
}
console.log(additem);
<form id="prd2">
<input type="hidden" name="product" value="et345">
<input type="hidden" name="name" value="Tshirt">
<select name="quantity"><option value="1">1</option><option value="2">2</option><option>etc</option></select><br>
<input type="hidden" name="img" value="img345">
<input type="hidden" name="optType" value="clothing">
<button id="btn2" type="submit" class="addcart">Add to Cart</button>
</form>