1

I'm trying to use JavaScript parameters in a function, but I'm not writing the syntax correctly.

This function is supposed to revert information in objects with the aa tag into whatever is specified with ba.

function myFunction(aa, ba){
    document.getElementById(aa).innerHTML = ba;
}

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="myFunction(demo, My First Javascript)">Click Me!</button>

4 Answers 4

2

Add single quotes around the inputs to your function:

Javascript:

function myFunction(aa, ba){
    document.getElementById(aa).innerHTML = ba;
}

html:

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

here's a link to a codepen.io demo: https://codepen.io/167141162/pen/Vrgvbg

Sign up to request clarification or add additional context in comments.

Comments

1

Strings in JavaScript must be wrapped in either "" or ''. In your example, JavaScript will think that you are trying to pass a variable (or a function) called demo for the first argument, and the second one (My First Javascript) will throw a SyntaxError.

So, this will work:

function myFunction(aa, ba){
    document.getElementById(aa).innerHTML = ba;
}
<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

Comments

0

Wrap your string parameters in single quotes

<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

Comments

0

Your parameter << demo >> must be in single quotes, because in the js file the parameters take it as strings <button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

4 Comments

Why add the same answer as 3 people before you ?
I did not read the page update that said there are 2 new answers, I was still writing ... :sweat_smile: , and yes now it's really unuseful
@Enzo_Lizama This happened with my answer too (@Denno answered a few seconds before me), but the thing is that your answer 7 mins after the first answers, so I thought it was otherwise. Sorry.
I went to bring food after reading the question and then started writing: smile:, no problem

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.