Jquery new Element Resulting in [object object] when concatenated - javascript

I am trying create a new Anchor tag in Jquery with some attribute and storing it in variable, but when i concatenate it with other variable and append to Dom it gives [OBJECT OBJECT]
JsFiddle for the Same :
http://jsfiddle.net/T8q6T/
var a_name = "Sathwick Rao (sgmdev#gmail.com)^$^4083372345";
var _name = a_name.split('(')[0];
var _part1 = a_name.split('(')[1];
var _email = _part1.split(')')[0];
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email);
$('#shara').html(_name+' '+htmlElement);

You can't concatenate a string with an object like that. Separate the two statements like this:
http://jsfiddle.net/E2Rur/
$('#shara').html(_name).append(htmlElement);

It's because you are trying to concatenate an object with a string. Therefore, the object gets implicitly converted to it's string representation by it's toString function.
E.g.
var div = document.createElement('div');
'some string' + div.toString(); //"some string[object HTMLDivElement]"
'some string' + div; //"some string[object HTMLDivElement]"
If you want to concatenate the outerHTML of the element with some other HTML string that is possible however.
$('#shara').html(_name + ' ' + htmlElement.prop('outerHTML'));
However it's not necessary the most optimal or clean way when it's not necessary.
$('#shara').append($('<span>').addClass('name').text(_name).add(htmlElement));
As you may have noticed, I add the htmlElement to the set and perform a single append operation rather than chaining two append calls. That's to avoid multiple DOM reflows, which are quite expensive.
If you do not want the wrapping span and use the same solution, you can also do:
$('#shara').append($(document.createTextNode(_name + ' ')).add(htmlElement));

To force the variable htmlElement to store a string, I sometimes hack it like this
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email)+"";
$('#shara').html(_name+' '+htmlElement);

Related

JavaScript - returning [object Object]

I'm working on a dynamic form that appends groups of input fields to the page based on user input. Because of some additional functionality that needs to be attached to some of these elements, I need to create them as JSON objects. When I test this method with only one input element, the element is appended to the page, no problem. However, when I try to incorporate a second element into the process, I get [object Object] [object Object] appended to the page instead.
Here's the gist...
//THIS IS THE PROBLEM FUNCTION, WHICH IS TRIGGERED BY THE CHANGE FUNCTION BELOW
function generateInput(siteNumber, x){
select = $("<select/>", {
id: 'select'+siteNumber+''+x+'',
name: 'select'+siteNumber+'['+x+']'
}).append(list);
notes = $("<input/>", {
type: 'text',
id: 'notes'+siteNumber+''+x+'',
name: 'notes'+siteNumber+'['+x+']'
});
//IF I RETURN ONE OR THE OTHER, NO PROBLEM
return select + notes;
};
$(document).on("change", ".number_select", function(){
siteNumber = $(this).parent().attr('data-site_number');
numberFound = $(this).val();
for(x = 1; x <= numberFound; x++){
this['inputArray' + siteNumber].push(generateInput(siteNumber, x));
};
$(this).parent().append(this['inputArray' + siteNumber]);
});
I imagine that the problem is with the way that I am returning the elements at the end of generateInput, but I'm not sure of the proper way to handle this. Basically, what I am aiming to get is the select element with the text element sitting next to it.
Thanks very much!
The + operator will call the toString() method of one of the terms if the other is a string.
This is not what you want, what you want instead is to merge the jQuery objects into one
Thus
return select + notes;
Could become (see jquery doc for add):
return select.add(notes);
If you have two objects and add them, they are cast to string using .toString() method, which returns string "[object Object]". It means this is an object, which is instance of Object. If you want to return both object, you can return them for example as array:
return [species, notes];
Then you can pass the result to the .push() method using spread operator:
this['inputArray' + siteNumber].push(...generateInput(siteNumber, x));
However, since the .push() method accepts many arguments, you don't even need to modify this part of code.

Convert string value into variable value - JavaScript

I have a string variable: id = '1';
I want to make a variable that holds the value of data.img + id + .dispWidth without making it a string.
For example, if id = '7'; then dw = data.img7.dispWidth;
How can I do this?
Use bracket notation to use dynamic property keys
dw = data['img' + id].dispWidth;
data['img' + id].dispWidth should do it. Although at that point you should probably consider whether you don't actually want an array.

Converting string to javascript object

I want my user to input some text in an input field and click a button "Evaluate" on clicking that button I will convert that inputted text into a JavaScript object if I could and will show all of it's members(properties and functions).
For example if user inputs "document" or "window" I will show all members of document and window respectively.
Iterating through the members of an object is done, but when user inputs some text in input text field and I get that text than that value is treated as String of course how can I convert that text into an object like "document" to document and "window" to window ???
You can use "eval". Edit: Thanks to the comments of #Victor and #Cerbrus for pointing out that eval is unnecessary here. You can also use window[input].
var input = "document";
var obj = eval(input);
for (var prop in obj) console.log(prop + ": " + obj[prop]);
If it's a member of another object (ie, a global object), then you can use the bracket-notation:
var hello = "world";
var variableName = "hello";
console.log(JSON.stringify(window[variableName]));
The proposed solution won't work for sub-properties (ex. window.document.body). I've written a small jsFiddle that should work for most cases. It certainly lacks real error checks but should be a decent place to start http://jsfiddle.net/a6A4m/1/
var showProperties = function(text) {
var output = '';
var object = window;
// if it isn't the global window object
if (text !== 'window') {
var parts = text.split('.');
// Since we're using pop, we need to reverse it first.
parts = parts.reverse();
while (parts.length > 0) {
object = object[parts.pop()];
}
}
$('#content').html(getOutput(object));
};
If you getting input value like that
var selector = $('input').val();
Then the object will be
$(selector)
If your string is JSON format, or the string is a name of javascript object, here a way I saw jQuery.parseJSON do to convert string to object.
var s2o = (new Function("return " +val+";"))();
suppose val contains the value from text input.
It's kind like using Function object as 'compiler', so that you get return a javascript object.
If user pass in document, it give out document object;
if user pass in {id:1, name:"test"}, it give out that object.

Converting an object in a loop to element and add it to the existing result

$.each(data, function(i,item){
var img = $('<img>');
img.attr('src', item.thumb);
img.attr('width', item.width);
img.attr('height', item.height);
o += '<li>'+img+'<h3>'+item.title+'</h3><p>'+item.excerpt+'</p></li>';
});
The above outputs
li>[object] <h3>title</h3><p>excerpt</p></li>
My problem is with image tag. I understand that I am just appending a image object rather than the element... and using appendto would work but in the above scenario, in a loop, how do I accomplish this. Instead of displaying [object] how can display the image tag.
That is a poor way to modify the DOM. You should use normal DOM methods so you don't get into this mess.
However, if you must do it that way.
The problem caused is an object's toString() being implicitly called which is specified to return [object [[Class]] where [[Class]] is the internal class of the object. That's why you get [object Object] instead of the HTML of the img element.
You could get the outer HTML like so...
var imgOuterHtml = img.prop('outerHTML')
|| '<img ' +
[]
.reduce
.call(img.prop('attributes'),
function(attrSerialised, attr) {
return attrSerialised +
' ' + attr.nodeName +
'="' + attr.nodeValue + '"';
},
'')
+ '/>';
jsFiddle.
It also looks like you can use new XMLSerializer().serializeToString(element) if the outerHTML property does not exist, but it will only ever return XML, e.g. empty elements are always empty.
You could also create a temporary element such as a div, set its innerHTML and then get the outer div's innerHTML.
But, please, don't do it this way. Use jQuery's wrapped DOM modifying methods.
you have to get the html out of the object. there's a dozen or more ways to do that. one way is img[0].outerHTML which gives you the raw DOM element in the jQuery selector object, and then the outer html of that element.
$.each(data, function(i,item){
var img = $('<img>');
img.attr('src', item.thumb);
img.attr('width', item.width);
img.attr('height', item.height);
o += '<li>'+img[0].outerHTML+'<h3>'+item.title+'</h3><p>'+item.excerpt+'</p></li>';
});

Viewing an object

I am learning JS and after fiddling around with adding elements etc I tried to do an alert() with the object but instead got this error: [object htmltableelement]
so I then tried:
alert(t.toString());
and got the same error... how can I see the contents of the object?
you can use firebug:
console.log(t);
or you can use innerHTML;
alert(t.innerHTML);
The way I normally do this is by using FireBug firefox add-on.
Add a break point in your JavaScript then you can view any object and all its keys/values.
See everything:
for(var key in t)
alert('key:' + key + ', value: ' + t[key]);
You may want to replace alert with console to avoid 100s of alerts
function domObjectToString(domObject){
if(typeof(domObject) ==='object'){
var divElement = document.createElement('div') ;
divElement.appendChild(domObject);
return divElement.innerHTML;
}else{
return domObject.toString();
}
}
---- steps follow -----
1. check the domObject Type [object]
2. If Object than
a. Create an "Div" element
b. append DomObject To It
c. get The innerHTML of the "div" it Gives The String
3. If Not an Object than convert to String and return it .
That is not an error. That is the default string representation of an object.
Either iterate through the object's properties and output them one by one, or use a proper debugging tool like Firebug that'll give you the ability to really examine your variables.

Categories