function showError(field, error) {
field.prepend(`<pre>Ошибка: ${error}</pre>`);
}
if (onlyDigits(last_name.val()) || last_name.val() == "") {
console.log('ошибка фамилии');
showError(last_name, allErrors.last_name);
return false;
} else {
return true;
}
<input name="last_name" required pattern="[А-ЯЁа-яё]+">
field.setCustomValidity("Минимум одна буква");
document.addEventListener('click', function myClickHandler(evt) { // слушаем все клики
if (evt.target.matches('.selector')){ // проверяем был ли это клик по .selector
// do your stuff
}
});
document.addEventListener('click', function myClickHandler(evt) { // слушаем все клики
const elem = evt.target.closest('.selector');
if (elem){ // если клик мимо, то тут null
// do your stuff
}
});
function test(a, b) {
console.log(a,b);
}
// вызов
test(5,10);
function test(obj) {
console.log(obj.a, obj.b);
}
// вызов
test({'a':5, 'b' :10});
document.addEventListener('click', function(evt) { // всего один EventListener
const btn = evt.target.closest('.box button');
if (btn) { // если клик не по кнопке, то в переменной будет null, и этот блок не выполнится.
btn.closest('.box') // ближайший родительский .box
.classList.toggle('active');
}
});
const links = [
'mysite.com/param/sometext-alt-text/otherparam/text?zzzz',
'mysite.com/param/foo/otherparam/qqqqqq',
'mysite.com/param/123/otherparam/jfghjfghk?...',
'mysite.com/param/foo/otherparam/gdfsghdfhkj',
'mysite.com/param1/sometext-alt-text/otherparam/text?zzzz',
'mysite.com/param2/foo/otherparam/qqqqqq',
'mysite.com/param/123/otherparam3/jfghjfghk?...',
'mysite.com/param/foo/otherparam4/gdfsghdfhkj',
];
const re = /param\/(?<param>.+)\/otherparam\/(?<otherparam>.*)/;
links.forEach(link => {
const found = link.match(re);
console.log(link, found);
});
<table>
<thead><th>id</th><th>delete</th></thead>
<tr>
{% for id in ids %}
<td>{{id}}</td>
<td><button>x</button></td>
{% endfor %}
</tr>
</table>
table.addEventListener('click', function(evt){
const btn = evt.target.closest('button');
if (btn) {
const id = btn.parentNode.previousElementSibling.textContent;
console.log({id});
}
});
$.ajax({
url: 'www.expample.ru/file.php',
type: 'POST',
data: { data: getSaveData() }, // переменная data не нужна
// ...
})
$.ajax({
url: 'www.expample.ru/file.php',
type: 'POST',
data: { data: $(form).serialize() },
// ...
})
$.ajax({
url: 'www.expample.ru/file.php',
type: 'POST',
data: { data: new FormData(form) },
// ...
})
const $form = $("#idForm");
$form.on('submit', function(evt) {
evt.preventDefault(); // отмена обычной отправки
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
// ...
const form = document.getElementById('myForm');
form.addEventListener('submit', function(evt){
evt.preventDefault();
fetch(form.action, {
method: 'POST',
body: new FormData(form)
});
});
let item = document.querySelector('li') // первый попавшийся li
// ...
item.classList.toggle('done') // именно ему вы и переключаете класс
const newLink = document.createElement('a');
newLink.href = '//google.com';
newLink.textContent = 'гугл';
newLink.title = 'поисковая система гугл';
document.body.append(newLink);
может есть вариант поэлегантней чем повторять
while (allTextNodes.nextNode()) {
replaceNodeText(allTextNodes.currentNode, text1, replaceValue);
replaceNodeText(allTextNodes.currentNode, text1, ClearText);
}
function replaceNodeText(node, search, replaceText) {
node.nodeValue = node.nodeValue.replace(search, replaceText);
}
FROM tbl SELECT *
который очевидно не сработает.function test() {
const a = [1];
return a[0] += 3; // что вы вернет?
}
a
?// с запятой
array.reduce((a,b,i)=>function(){
const sum = a[i%2] + b; // вычисление
a[i%2] = sum; // присваивание
return a; // возврат массива
}, [0,0]);
// без запятой
array.reduce((a,b,i)=>function(){
const sum = a[i%2] + b; // вычисление
a[i%2] = sum; // присваивание
return sum; // возврат результат суммирования
// и на следующей итерации будет ошибка из-за попытки обратиться к числу как к массиву.
}, [0,0]);