Skip to content
Advertisement

javascript arguments passed as objects instead of strings

Please help me understand how this could happen: I think I’m passing simple strings to a Javascript function, but they are received as form objects! The first argument is the id of the form. The second argument is the name of an input.

var div = document.getElementById('demo');
var elCheckbox = document.createElement('input');
var myFormId = 'hi', myInputName = 'bye';

console.log(typeof myFormId);       // logs: string
console.log(typeof myInputName);    // logs: string

elCheckbox.setAttribute('onclick','toggleHideField(' + myFormId + ', ' + myInputName + ');');
document.getElementById('hi').appendChild(elCheckbox);

function toggleHideField(formId,formFieldName) {
  console.log(formId + " " + formFieldName); // logs: [object HTMLFormElement] [object HTMLTextAreaElement]
}

I’m expecting string string instead.

Advertisement

Answer

When you concatenate the variables into the onclick attribute, they will be treated as variables because they’re not quoted. So you get

toggleHideField(hi, bye);

You want

toggleHideField('hi', 'bye');

But rather than concatenating strings, you should use addEventListener with a closure:

elCheckbox.addEventListener('click', function() { 
  toggleHideField(myFormId, mhyInputName); 
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement