Mooflemoos247
Mooflemoos247

Reputation: 11

Im trying to make a text box that you enter your email in and then it randomizes the email platform @ on the end when you click a button

I am relatively new to JavaScript and I'm unsure how to save what you typed in the text box in a variable and then add an @ to the end (e.g. you enter in mooflemoos247 and then you click the button and it runs a function that adds a random @ to the end such as @gmail.com).

I am also new to stackoverflow so let me know if I am asking the question right.

I currently have:

document.getElementById("textBox").value = document.getElementById("textBox").value + email[Math.floor(Math.random() * email.length)]

I understand that when I am adding the @ and then making the @ part of the variable but I don't know a way around that. Thanks for the help :)

Upvotes: 1

Views: 75

Answers (2)

user15260712
user15260712

Reputation:

try this

    

    let array = ["@gmail.com","@yahoo.com","@example.com"];
    
    function add(){
    let input_field = document.getElementById("email");
    let input_value = input_field.value.split("@")[0];
      input_field.value = input_value + array[Math.floor(Math.random() * array.length)]
    }
    
    <input type="text" id="email" />
    <button onclick="add()">Add @</button>

Upvotes: 0

DecPK
DecPK

Reputation: 25408

First of all, you need to check if there is already any email provider appended to the string or not. If yes then get the address before @ and append it with random email service provider.

const input = document.querySelector("#textBox");
const button = document.querySelector("button");

const emailProviders = [
  "gmail.com",
  "yahoo.com",
  "hotmail.com",
  "aol.com",
  "msn.com",
  "outlook.com",
  "live.com"
]

button.addEventListener("click", () => {
  let inputValue = input.value;
  
  if (inputValue.match(/@/)) inputValue = inputValue.split("@")[0];
  
  input.value = `${inputValue}@${emailProviders[Math.floor(Math.random() * emailProviders.length)]}`;
})
<input type="text" id="textBox" />
<button> Append text </button>

Upvotes: 1

Related Questions