Помогите разобраться со скриптами javascript
Как вывести email фрагментами начиная с первого символа и увеличивая количество символов с каждой итерацией (с помощью substring), а также в обратном порядке? (Работаю в VS Code.)
Вот пример:
Вот мой код:
function getValueById(id) {
return document.getElementById(id).value;
}
function setValueById(id, value, append = true) {
let element = document.getElementById(id);
element.value = append ?
element.value + value + "\n" :
value + "\n";
}
function btnSubmitOnClick() {
let firstName = getValueById("txtFirstName");
let lastName = getValueById("txtLastName");
let User = 'User: ';
let fullName = firstName + lastName;
setValueById("txtResult", User + fullName);
let Email = getValueById("txtEmail");
let mail = 'Email: ';
setValueById("txtResult", mail + Email);
let yearOfBirth = getValueById("txtYearOfBirth");
let years = 'Age: ';
let age = new Date().getFullYear() - yearOfBirth;
let tage;
if (age > 0) {
tage = 'Baby';
}
if (age > 2) {
tage = 'Toddler';
}
if (age > 4) {
tage = 'Kid';
}
if (age > 10) {
tage = 'Tween';
}
if (age > 13) {
tage = 'Teen';
}
if (age > 19) {
tage = 'Young Adult';
}
if (age > 21) {
tage = 'Adult';
}
let stage = 'Age stage: ';
setValueById("txtResult", years + age);
setValueById("txtResult", stage + tage);
let currentYear = new Date().getFullYear();
if (yearOfBirth > currentYear) {
alert('Year Of Birth can’t be more than current year');
}
if (lastName == false) {
alert('The <parameter label> is required.');
}
if (Email == false) {
alert('The <parameter label> is required.');
}
if (firstName == false) {
alert('The <parameter label> is required.');
}
if (yearOfBirth == false) {
alert('The <parameter label> is required.');
}
}
.container {
float: left;
}
.row {
margin-top: 10px;
clear: both;
text-align: right;
}
.row label {
float: left;
}
.row>input {
margin-left: 10px;
}
<div class="container">
<div class="row">
<label>First Name: </label><input id="txtFirstName" />
</div>
<div class="row">
<label>Last Name: </label><input id="txtLastName" />
</div>
<div class="row"><label>Email: </label><input id="txtEmail" />
</div>
<div class="row"><label>Year Of Birth:</label><input id="txtYearOfBirth" />
</div>
<div class="row">
<input id="btnSubmit" type="button" value="Submit" onclick="btnSubmitOnClick();" />
</div>
<div class="row">
<textarea id="txtResult" cols="35" rows="45"></textarea>
</div>
</div>
Ответы (2 шт):
Автор решения: Andrey Semykin
→ Ссылка
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.container {
float: left;
}
.row {
margin-top: 10px;
clear: both;
text-align: right;
}
.row label {
float: left;
}
.row>input {
margin-left: 10px;
}
</style>
<script>
function getValueById(id) {
return document.getElementById(id).value;
}
function setValueById(id, value, append = true) {
let element = document.getElementById(id) ;
element.value = append
? element.value + value + "\n"
: value + "\n";
}
function btnSubmitOnClick() {
let firstName = getValueById("txtFirstName");
let lastName = getValueById("txtLastName");
let User = 'User: ';
let fullName = firstName + lastName;
setValueById("txtResult", User + fullName);
let Email = getValueById("txtEmail");
let mail = 'Email: ';
setValueById("txtResult", mail + Email);
let yearOfBirth = getValueById("txtYearOfBirth");
let years = 'Age: ';
let age = new Date().getFullYear() - yearOfBirth;
let tage;
if (age > 0) {
tage = 'Baby';
}
if (age > 2) {
tage = 'Toddler';
}
if (age > 4) {
tage = 'Kid';
}
if (age > 10) {
tage = 'Tween';
}
if (age > 13) {
tage = 'Teen';
}
if (age > 19) {
tage = 'Young Adult';
}
if (age > 21) {
tage = 'Adult';
}
let stage = 'Age stage: ';
setValueById("txtResult", years + age);
setValueById("txtResult", stage + tage);
printEmail(Email);
let currentYear = new Date().getFullYear();
if (yearOfBirth > currentYear) {
alert('Year Of Birth can’t be more than current year');
}
if (lastName == false) {
alert('The <parameter label> is required.');
}
if (Email == false) {
alert('The <parameter label> is required.');
}
if (firstName == false) {
alert('The <parameter label> is required.');
}
if (yearOfBirth == false) {
alert('The <parameter label> is required.');
}
}
function printEmail(email){
let length = email.length;
for (let i=1; i<=length; i++){
setValueById("txtResult", email.substr(0, i));
}
for (let i=length; i>=0; i--){
setValueById("txtResult", email.substr(0, i));
}
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<label>First Name: </label><input id="txtFirstName"/>
</div>
<div class="row">
<label>Last Name: </label><input id="txtLastName"/>
</div>
<div class="row"><label>Email: </label><input id="txtEmail"/>
</div>
<div class="row"><label>Year Of Birth:</label><input id="txtYearOfBirth"/>
</div>
<div class="row">
<input id="btnSubmit" type="button" value="Submit"
onclick="btnSubmitOnClick();"/>
</div>
<div class="row">
<textarea id="txtResult" cols="35" rows="45"></textarea>
</div>
</div>
</body>
</html>
Автор решения: Aleksandr Belous
→ Ссылка
Держи. Может еще что-то интересное для себя почерпнешь)
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.container {
float: left;
}
.row {
margin-top: 10px;
clear: both;
text-align: right;
}
.row label {
float: left;
}
.row>input {
margin-left: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<label>First Name: </label><input id="txtFirstName"/>
</div>
<div class="row">
<label>Last Name: </label><input id="txtLastName"/>
</div>
<div class="row"><label>Email: </label><input id="txtEmail"/>
</div>
<div class="row"><label>Year Of Birth:</label><input id="txtYearOfBirth"/>
</div>
<div class="row">
<input id="btnSubmit" type="button" value="Submit" onclick="btnSubmitOnClick();"/>
</div>
<div class="row">
<textarea id="result" cols="35" rows="45" disabled></textarea>
</div>
</div>
<script>
const resultField = document.getElementById('result')
const clearResults = () => resultField.value = ''
const getFieldValue = (fieldId) => document.getElementById(fieldId).value
const getStage = (age) => {
if (age < 0) throw new Error('Cant calculate age stage: Invalid age')
if (age <= 2) return 'Baby'
if (age <= 4) return 'Toddler'
if (age <= 10) return 'Kid'
if (age <= 13) return 'Tween'
if (age <= 19) return 'Teen'
if (age <= 21) return 'Young Adult'
if (age > 21) return 'Adult'
}
const calculateAge = (birthYear) => new Date().getFullYear() - birthYear
const generateLadder = (string) => {
let result = ''
for (let i = 1; i < string.length; i += 1) {
result += `${string.substring(0, i)}\n`
}
for (let i = string.length - 1; i >= 0; i -= 1) {
result += `${string.substring(0, i)}\n`
}
return result
}
const generateResult = (firstName, lastName, email, age) => {
const userStroke = `User: ${firstName} ${lastName}`
const emailStroke = `Email: ${email}`
const ageStroke = `Age: ${age}`
const ageStageStroke = `Age stage: ${getStage(age)}`
return `${userStroke}\n${emailStroke}\n${ageStroke}\n${ageStageStroke}\n${generateLadder(email)}`
}
const isValuesNotEmpty = (...values) => values
.reduce((acc, value) => {
if (acc) {
return value.trim() !== ''
}
return false
}, true)
function btnSubmitOnClick() {
clearResults()
const firstName = getFieldValue('txtFirstName')
const lastName = getFieldValue('txtLastName')
const email = getFieldValue('txtEmail')
const birthYear = getFieldValue('txtYearOfBirth')
const age = calculateAge(birthYear)
const isDataValid = isValuesNotEmpty(firstName, lastName, email, birthYear)
if (!isDataValid) return alert('All fields are required')
if (age <= 0) return alert('Set correct birth year')
resultField.value = generateResult(firstName, lastName, email, age)
}
</script>
</body>
</html>
