0

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.

1
  • @MisterJojo - Sorry, trying to keep it simple. The post is updated. Commented Sep 28, 2022 at 21:56

1 Answer 1

1

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); 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.