filterInput.addEventListener('keyup',...
пусть будетfilterInput.addEventListener('input', function() {
const value = this.value.toLowerCase();
filterResult.innerHTML = resultArr
.filter(n => n.toLowerCase().includes(value))
.map(n => `<li>${n}</li>`)
.join('');
});
value=""
. Соответственно, проверять надо будет value на пустоту, а не равенство тексту. Это и проще, и код не придётся переписывать, если вдруг завтра вам потребуется изменить текст по умолчанию..element
), а не каждому элементу индивидуально. Не придётся вписывать новый обработчик или удалять существующий, если изменится количество элементов в форме.button.disabled = ![
inputMail.value,
inputPhone.value,
select.value,
checkbox.checked,
].every(Boolean);
str.match(/(?<=\{{2}).+?(?=\}{2})/g) ?? []
// или
Array.from(str.matchAll(/\{\{(.+?)\}\}/g), n => n[1])
document.querySelectorAll('.cart__counter').forEach(n => {
n.innerText = parseInt(n.innerText);
});
[...params.keys()].forEach(n => whiteList.includes(n) || params.delete(n));
const deleteTextNodes = el =>
el.nodeType === 3
? el.remove()
: [...el.childNodes].forEach(deleteTextNodes);
if (total_sum >= rand) {
function getRandom(arr, key) {
const rand = Math.random() * arr.reduce((acc, n) => acc + n[key], 0);
let sum = 0;
return arr.find(n => (sum += n[key]) > rand);
}
const obj = getRandom(data, 'weight');
let isBtn1Clicked = false;
button1.addEventListener('click', () => isBtn1Clicked = true);
button2.addEventListener('click', () => {
if (isBtn1Clicked) {
// ...
}
});
button1.addEventListener('click', e => e.target.classList.add('clicked'));
button2.addEventListener('click', () => {
if (button1.classList.contains('clicked')) {
// ...
}
});
button2.disabled = true;
button1.addEventListener('click', () => button2.disabled = false);
button2.addEventListener('click', () => {
// ...
});
button2.hidden = true;
button1.addEventListener('click', () => button2.hidden = false);
button2.addEventListener('click', () => {
// ...
});
button1.addEventListener('click', () => {
button2.addEventListener('click', () => {
// ...
});
}, { once: true });
const obj = Object.fromEntries(arr.map(n => [ n.name, n.number ]));
// или
const obj = arr.reduce((acc, n) => (acc[n.name] = n.number, acc), {});
// или
const obj = Object.assign({}, ...arr.map(n => ({ [n.name]: n.number })));
function toObj(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const obj = {};
for (const n of data) {
obj[getKey(n)] = getVal(n);
}
return obj;
}
const obj = toObj(arr, 'name', 'number');
// {Kolya: '5', Olga: '10'}
const charCodes = toObj('abc', n => n.charCodeAt());
// {97: 'a', 98: 'b', 99: 'c'}
<input name="xxx" value="69">
<input name="yyy" value="187">
<input name="zzz" value="666">
const inputValues = toObj(document.querySelectorAll('input'), 'name', 'value');
// {xxx: '69', yyy: '187', zzz: '666'}
const prices = {
'Москва': 100,
'Санкт-Петербург': 200,
'Казань': 300,
};
$('form').on('change', function() {
const [ city1, city2 ] = $('select', this).get().map(n => n.value);
const price = city1 === city2
? prices[city1]
: prices[city1] + prices[city2];
$('input', this).val(price);
}).change();
button.addEventListener('click', async () => {
for (const el of cards) {
await el.animate([
{ transform: 'rotateX(0deg)' },
{ transform: 'rotateX(180deg)' },
], {
duration: 1000,
easing: 'linear',
fill: 'forwards',
}).finished;
}
});
const container = document.querySelector('.buttons');
const buttonSelector = '.button';
const onButtonClick = button => console.log(button.id);
container.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
onButtonClick(button);
}
});
container.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => onButtonClick(e.currentTarget));
Например если число 200000
const bullshitDateFormat = str =>
new Date(+str.replace(/\D/g, ''))
.toLocaleString('ru-RU')
.slice(0, -3)
.replace(',', '');
.slice(0, -3)
выглядит сильно так себе (с другой стороны - коротко), вместо него можно в явном виде (второй параметр) указать при вызове toLocaleString, какие элементы даты надо получить:{
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}
Object.values(arr.reduce((acc, n) => {
const name = n.name.split(' ').pop();
acc[name] = +acc[name]?.price < +n.price ? acc[name] : n;
return acc;
}, {}))
const result = arr.flat().map((n, i) => ({ ...n, id: -~i }));
const result = [];
for (const n of arr) {
for (const m of n) {
result.push({
...m,
id: result.length + 1,
});
}
}
const coord = [ 0, 0 ];
const step = 10;
const moveFunc = e => {
const shift = ({
ArrowUp: [ 0, -1 ],
ArrowDown: [ 0, 1 ],
ArrowLeft: [ -1, 0 ],
ArrowRight: [ 1, 0 ],
})[e.code];
if (shift) {
div.style.left = `${coord[0] += shift[0] * step}px`;
div.style.top = `${coord[1] += shift[1] * step}px`;
}
};