Один из вариантов - использовать регулярное выражение: проверьте, соответствует ли [^a-z ]
вводу (то есть, есть ли какие-либо символы, кроме букв и пробелов). Если есть совпадение, покажите ошибку и немедленно вернитесь (не переходите к циклу или оператору switch
):
if (/[^a-z ]/i.test(workout)) {
exercise.textContent = 'Please enter letters and spaces only';
return;
}
function myFunction() {
const myArray = ["60", "50", "20", "30", "15", "10"];
const workout = document.getElementById("myInput").value;
const exercise = document.getElementById("excercise");
if (/[^a-z ]/i.test(workout)) {
exercise.textContent = 'Please enter letters and spaces only';
return;
}
let text = "";
for (const char of workout.toUpperCase()) {
const randomJumpingJacks = myArray[Math.floor(Math.random() * myArray.length)];
const randomCrunches = myArray[Math.floor(Math.random() * myArray.length)];
switch (char) {
case "A":
case "I":
case "N":
case "X":
text += randomJumpingJacks;
text += " Jumping Jacks";
break;
case "B":
case "J":
case "Q":
case "Y":
text += randomCrunches;
text += " Crunches";
break;
case " ":
/*text += " break ";*/
break;
default:
text += "Place holder for Error Text ...";
}
text += " "
text += "<br>"
}
document.getElementById("excercise").innerHTML = text;
}
<p>Input some characters and click the button.</p>
<p>Your excericse routine will display based on your input.</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Try it</button>
<p>
<span id="reps"></span>
<span id="excercise"></span>
</p>