lboyel
lboyel

Reputation: 2228

Jquery returns [object object] when trying to manipulate dom

I am trying to dynamically insert html fragment(input element) into an already existing div node.

I need to create three input elements, so I am using a loop to create them and initialize them via jquery. I am storing the created elements in a variable called htmlstr.

 var Buildstorecontents = function Buildstorecontents ()
    {

      var $parts_holder = $("#parts_holder");
      var $htmlstr = "";
      for(var i = 0; i < 3; i += 1)
      {
        $htmlstr += $("<input />", {
          "type"  : "text",
          "class" : "",
          "readonly"  : true
         }).append($("<br />"));
      }
      console.log($htmlstr);
      $parts_holder.append($htmlstr);
     }
     Buildstorecontents();

The problem is the variable htmlstr isn't holding the created html node but rather [object object]. What is the mistake I am making and other possible ways to do this?

This is what I am trying to achieve

<div id="parts_holder">        
  <input type="text" class="" readonly/><br /> 
  <input type="text" class="" readonly/><br />
  <input type="text" class="" readonly/><br />
</div>    

Upvotes: 0

Views: 2688

Answers (2)

Justin Niessner
Justin Niessner

Reputation: 245459

Your mistake is expecting the result of the jQuery operations to be a string.

You should create your entire HTML string before passing it to jQuery:

var htmlString = "";
for (var i = 0; i < 3; i++) {
    htmlString += "<input type='text' class='' readonly /><br />";
}
$parts_holder.append($(htmlString));

It will cut down on the number of individual DOM manipulations performed by jQuery and speed everything up.

And just in case you want to see things in action:

JSFiddle

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 237995

You're trying to concatenate a jQuery object to a string. This won't work, because a jQuery object does not have a useful toString value.

You need to create an empty jQuery collection, add the elements to that, and then append that collection.

  var $html = $();
  for(var i = 0; i < 3; i += 1)
  {
    $html = $html.add($("<input />", {
      "type"  : "text",
      "class" : "",
      "readonly"  : true
     })).add($("<br />"));
  }
  console.log($html);
  $parts_holder.append($html);

Upvotes: 4

Related Questions