Search code examples
javascriptsubstringalertprompt

Button, Prompt, and Alert


I have a button element in my html that looks like this:

<button id = "buttonOne" type = "button" onclick = "buttonOne()">
Click Me!
</button>

I have a function in my js file that looks like this:

function buttonOne() {

    var input = prompt("Please enter your first name followed by a comma and then 
    your age (ex. Mikey, 12):");

    var name = input.substring(0, indexOf(","));

    alert(name);
}

What I am trying to do is alert only the name retrieved from the prompt. However, my button does not seem to be activating the prompt anymore.


Solution

  • function buttonOne() {
      var input = prompt("Please enter your first name followed by a comma and then your age (ex. Mikey, 12):");
      var name = input.substring(0, input.indexOf(","));
      if(name){
        alert(name);
      }else{
        alert('Uh huh.. please enter in correct format');
      }
    }
    <button id="buttonOne" type="button"onclick="buttonOne()">
      Click Me!
    </button>

    You need to use the following to get the name.

    var name = input.substring(0, input.indexOf(","));