1

I have this code:

 jsonObj = [];
 $("#test").find('.data').each(function() {

    var description = $(this).find('.description').val();
    var food = $(this).find('.food').val();

    item = {}
    item ["description"] = description;
    item ["food"] = food;

    jsonObj.push(item);
});

Internet explorer 11 inserts empty/null values. of-course it works well in chrome firefox or even in edge

user3553470
  • 107
  • 9
  • 1
    "inserts empty/null values" — Where? Given what input? How / when are you testing this? – Quentin Jan 31 '17 at 10:32
  • I can verify the OP's claim about IE11 with this: https://jsfiddle.net/vdnhxhLo/ – T.J. Crowder Jan 31 '17 at 10:36
  • Side note: `jsonObj` is an odd name for a variable whose value is not JSON. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. Your `jsonObj` is an array. – T.J. Crowder Jan 31 '17 at 10:47

1 Answers1

1

I can replicate the issue using your code in this fiddle in IE11.

The problem is that you haven't declared item, and so you're using a global item (thanks to The Horror of Implicit Globals1), which is predefined in IE11 as a native function you can't overwrite or add properties to (this one, according to this page). It's not predefined (or is overwritable) in other browsers.

The lesson here is: Declare your variables. :-) If you do that, it works on IE11 as well (updated fiddle):

var jsonObj = []; // ***
 $("#test").find('.data').each(function() {

    var description = $(this).find('.description').val();
    var food = $(this).find('.food').val();

    var item = {}  // ***
    item ["description"] = description;
    item ["food"] = food;

    jsonObj.push(item);
});
$("<pre>").text("Result: " + JSON.stringify(jsonObj, null, 2)).appendTo(document.body);
<div id="test">
  <div class="data">
    <input type="text" class="description" value="description1">
    <input type="text" class="food" value="food1">
  </div>
  <div class="data">
    <input type="text" class="description" value="description2">
    <input type="text" class="food" value="food2">
  </div>
  <div class="data">
    <input type="text" class="description" value="description3">
    <input type="text" class="food" value="food3">
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>

1 That's a post on my anemic little blog.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875