Home > Enterprise >  javascript arguments passed as objects instead of strings
javascript arguments passed as objects instead of strings

Time:09-29

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.

CodePudding user response:

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); 
});
  • Related