Home > front end >  why does this javascript function keep failing
why does this javascript function keep failing

Time:01-22

 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

CodePudding user response:

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.

CodePudding user response:

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>

  •  Tags:  
  • Related