-1
 function greeting(name, time) {
    const greet = alert("hello" + " " + name + " " + "Good" + " " + time);
    return greeting;
  }
  greeting(Kofo, Morning);
  document.getElementById("p1").innerHTML = greeting;
</script>
<button onclick="greeting()">Click me</button>
<p id="greet"></p>

My code keeps failing and bringing back undefined

  • 1
    `greeting(Kofo, Morning);` <--- because you have a variable Kofo and a variable Morning... not strings. After that, alert does not return anything. After that you are setting innerHTML of an element before it exists. There is no elment in your code with the id of 'p1' – epascarello Jan 21 '22 at 13:55
  • What you want to achieve? You are returning "greeting" from function which is name of function itself. – ShriHans Jan 21 '22 at 14:00
  • @epascarello hi I am new to javascript and I have watched 4 videos on function. I am attempting to get an alert on a button that says name and time when clicked. This keeps failing and I have been on this for over 1 hour, Its so silly cause I could do this before but took a break now I don't understand anymore. Could you share with me the working code to compare? – Kofoworola GT Kofo Jan 21 '22 at 14:06
  • @ShriHans I am trying to make it say hello kofo good morning on the alert when clicked. I am new to javascript I was learning it last year but took a break for Christmas and cannot remember this anymore. – Kofoworola GT Kofo Jan 21 '22 at 14:08

2 Answers2

0

Problem 1

greeting(Kofo, Morning);

You are calling greeting (not when the button is clicked, just when the script runs) and are passing it two variables.

You haven't defined those variables so the script is going to throw a reference error and stop.

Possibly you want to use string literals, which would have quotes around them.

You said you wanted the alert to happen when the button is pushed, so probably you don't want that line of code at all.

Problem 2

document.getElementById("p1").innerHTML = greeting;

This will error. See Why does jQuery or a DOM method such as getElementById not find the element?.

You don't have an element with that ID at all, let alone at the time the script runs.

Problem 3

onclick="greeting()"

This time, you aren't passing any arguments at all.

name and time are going to be undefined.


onclick and other intrinsic event attributes come with a bunch of gotchas and are far from best practise.

You should switch to using addEventListener.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

This code will do what you want to achieve.

<script>
function greeting(name, time) {
    const greet = alert("hello" + " " + name + " " + "Good" + " " + time);

  }
</script>
<button onclick="greeting('Kofo', 'Morning')">Click me</button>
<p id="greet"></p>
ShriHans
  • 89
  • 4