проверка type="radio"
Как сделать что бы при нажатие на кнопку была проверка все ли нажаты радио батны, если что то не нажато к ней плавно подъехать(к самой верхней), с отступом в 60 пикселей и выделить каким нибудь цветом что они не выбраны.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Radio Button</title> <style> .test{ height: 2000px; } .test2{ height: 200px; } </style> </head> <body> <form> <input type="radio"> <div class="test2"></div> <input type="radio"> <div class="test2"></div> <input type="radio"> <div class="test"></div> <button type="submit">Submit</button> </form> <script> const form = document.querySelector('form'); const input = document.querySelector('input[type="radio"]'); form.addEventListener('submit', (event) => { if (!input.checked) { event.preventDefault(); input.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest', }); input.style.marginTop = '60px'; } }); </script> </body> </html> |
И почему то этот scrollIntoView не работает
|
CSS:
input[type="radio"] { scroll-margin-top: 10px; } JS: const form = document.querySelector('form'); form.addEventListener('submit', (event) => { const firstCheckedElement = form.querySelector('input[type="radio"]:not(:checked)'); if (firstCheckedElement !== null) { event.preventDefault(); firstCheckedElement.scrollIntoView({ behavior: 'smooth', }); } }); |
Зачем делать одиночные радиокнопки? Одиночными обычно чекбоксы бывают. А радио - это именно выбор одного из нескольких.
|
Цитата:
|
ruslan_mart,
А почему она не плавное едет а резко, и у самой в верхней нет отступа, только у тех кто ниже |
voraa,
Это я понимаю |
Цитата:
https://developer.mozilla.org/ru/doc...gin_collapsing |
Спасибо сделал то что нужно. Вот код вдруг кому понадобится. Если что спрашивайте.
document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); const radioButtons__1 = document.querySelectorAll("input[type='radio']"); radioButtons__1.forEach(function(radioButton) { if (!radioButton.checked) { radioButton.parentElement.classList.add("not_marked"); } }); event.preventDefault(); var radioButtons__2 = document.querySelectorAll('.check'); var firstUnchecked = null; for (var i = 0; i < radioButtons__2.length; i++) { if (!radioButtons__2[i].checked) { firstUnchecked = radioButtons__2[i]; break; } } if (firstUnchecked) { var parentDiv = firstUnchecked.parentElement; parentDiv.classList.add('padding'); $('html, body').animate({ scrollTop: $(parentDiv).offset().top }, 500); } }); var radioButtons = document.querySelectorAll('.check'); radioButtons.forEach(function(radioButton) { radioButton.addEventListener('click', function() { var parentDiv = this.parentElement; parentDiv.classList.remove('padding'); }); }); |
Ни как не получается вот код
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Check input</title> <style> .margin_big { height: 1000px; } .margin_small { height: 200px; } .radio { margin: 60px 0px 0px 0px; } .form_radio { margin-bottom: 10px; } .form_radio input[type=radio] { display: none; } .form_radio label { display: inline-block; cursor: pointer; position: relative; padding-left: 25px; margin-right: 0; line-height: 18px; user-select: none; } .form_radio label:before { content: ""; display: inline-block; width: 17px; height: 18px; position: absolute; left: 0; bottom: 1px; background: url(https://q-control.ru/allant/picture/radio-1.png) 0 0 no-repeat; } /* Checked */ .form_radio input[type=radio]:checked+label:before { background: url(https://q-control.ru/allant/picture/radio-2.png) 0 0 no-repeat; } /* Hover */ .form_radio label:hover:before { filter: brightness(120%); } /* Disabled */ .form_radio input[type=radio]:disabled+label:before { filter: grayscale(100%); } .not_marked label:before{ content: ""; background: url(https://q-control.ru/allant/picture/radio-3.png) 0 0 no-repeat; } .padding{ padding: 60px 0px 0px 0px; } </style> </body> </head> <body> <form> <div class="form_radio"> <input id="radio-1" type="radio" name="radio-1" value="1" class="check"> <label for="radio-1">Radio button 1</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-2" type="radio" name="radio-2" value="1" class="check"> <label for="radio-2">Radio button 2</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-3" type="radio" name="radio-3" value="1" class="check"> <label for="radio-3">Radio button 3</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-4" type="radio" name="radio-4" value="1" class="check"> <label for="radio-4">Radio button 4</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-5" type="radio" name="radio-4" value="1" class="check"> <label for="radio-5">Radio button 4</label> </div> <div class="margin_big"></div> <button type="submit">Submit</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <script type="text/javascript" src="https://q-control.ru/allant/js/jquery-1.11.1.min.js"></script> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); // предотвращает отправку формы const radioButtons__1 = document.querySelectorAll("input[type='radio']"); radioButtons__1.forEach(function (radioButton) { if (!radioButton.checked) { // если радиокнопка не отмечена radioButton.parentElement.classList.add("not_marked"); // добавляем класс not_marked к родительскому элементу радиокнопки } }); event.preventDefault(); // предотвращает отправку формы var radioButtons__2 = document.querySelectorAll('.check'); var firstUnchecked = null; for (var i = 0; i < radioButtons__2.length; i++) { if (!radioButtons__2[i].checked) { // если чекбокс не отмечен firstUnchecked = radioButtons__2[i]; // сохраняем первый неотмеченный чекбокс в переменную firstUnchecked break; } } if (firstUnchecked) { // если есть неотмеченные чекбоксы var parentDiv = firstUnchecked.parentElement; // сохраняем родительский элемент первого неотмеченного чекбокса в переменную parentDiv parentDiv.classList.add('padding'); // добавляем класс padding к родительскому элементу первого неотмеченного чекбокса $('html, body').animate({ // анимация прокрутки страницы к родительскому элементу первого неотмеченного чекбокса scrollTop: $(parentDiv).offset().top }, 500); } }); var radioButtons = document.querySelectorAll('.check'); radioButtons.forEach(function (radioButton) { radioButton.addEventListener('click', function () { // при клике на любую чекбокс кнопку var parentDiv = this.parentElement; // сохраняем родительский элемент чекбокса в переменную parentDiv parentDiv.classList.remove('padding'); // удаляем класс padding у родительского элемента этой чекбокс кнопки }); }); </script> </body> </html> мне нужно что бы если name у радио кнопок один и тот же как примеру тут name="radio-4" он одинаковый, и когда была выбрана одна из этих кнопок где имя одно и тоже не чего не происходило. Вот не чего же не происходит когда я выбираю радио кнопку к примеру name="radio-1" а когда не выбираю name="radio-1" меня скролик к ней Вот мне нужно если с одним и тем же именем я выбрал одну из кнопок то тоже не чего не происходило |
Это код работает так если кнопка не выбрана, то идет к ней скролл и остальные помечаются что не выбранные.
но если у радио кнопок name один то а в этом случае выбрать можно только одну кнопку, то все равно будет скрол которая не выбрна, а так не нужно |
Проверять не только саму кнопку, но и другие с этим же именем.
Как то так. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Check input</title> <style> .margin_big { height: 1000px; } .margin_small { height: 200px; } .radio { margin: 60px 0px 0px 0px; } .form_radio { margin-bottom: 10px; } .form_radio input[type=radio] { /*display: none;*/ } .form_radio label { display: inline-block; cursor: pointer; position: relative; padding-left: 25px; margin-right: 0; line-height: 18px; user-select: none; } .form_radio label:before { content: ""; display: inline-block; width: 17px; height: 18px; position: absolute; left: 0; bottom: 1px; background: url(https://rakipov.ru/public_htm/q-control/allant/picture/radio-1.png) 0 0 no-repeat; } /* Checked */ .form_radio input[type=radio]:checked+label:before { background: url(https://rakipov.ru/public_htm/q-control/allant/picture/radio-2.png) 0 0 no-repeat; } /* Hover */ .form_radio label:hover:before { filter: brightness(120%); } /* Disabled */ .form_radio input[type=radio]:disabled+label:before { filter: grayscale(100%); } .not_marked label:before{ content: ""; background: url(https://rakipov.ru/public_htm/q-control/allant/picture/radio-3.png) 0 0 no-repeat; } .padding{ padding: 60px 0px 0px 0px; } </style> </body> </head> <body> <form> <div class="form_radio"> <input id="radio-1" type="radio" name="radio-1" value="1" class="check"> <label for="radio-1">Radio button 1</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-2" type="radio" name="radio-2" value="1" class="check"> <label for="radio-2">Radio button 2</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-3" type="radio" name="radio-3" value="1" class="check"> <label for="radio-3">Radio button 3</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-4" type="radio" name="radio-4" value="1" class="check"> <label for="radio-4">Radio button 4</label> </div> <div class="margin_small"></div> <div class="form_radio"> <input id="radio-5" type="radio" name="radio-4" value="1" class="check"> <label for="radio-5">Radio button 4</label> </div> <div class="margin_big"></div> <button type="submit">Submit</button> </form> <script> const form = document.querySelector('form'); // Проверяем отмечена ли сама кнопка или другая с таким же именем const isCheck = (rbut) => { if (rbut.checked) return true; const rbuts = form.elements[rbut.name]; if (rbuts.length>1) { for (let i=0; i<rbuts.length; i++) if (rbuts[i].checked) return true; } return false; } form.addEventListener('submit', function (event) { event.preventDefault(); // предотвращает отправку формы const radioButtons__1 = document.querySelectorAll("input[type='radio']"); radioButtons__1.forEach(function (radioButton) { if (!isCheck(radioButton)) { // если радиокнопка не отмечена radioButton.parentElement.classList.add("not_marked"); // добавляем класс not_marked к родительскому элементу радиокнопки } }); event.preventDefault(); // предотвращает отправку формы var radioButtons__2 = document.querySelectorAll('.check'); var firstUnchecked = null; for (var i = 0; i < radioButtons__2.length; i++) { if (! isCheck(radioButtons__2[i])) { // если чекбокс не отмечен firstUnchecked = radioButtons__2[i]; // сохраняем первый неотмеченный чекбокс в переменную firstUnchecked break; } } if (firstUnchecked) { // если есть неотмеченные чекбоксы var parentDiv = firstUnchecked.parentElement; // сохраняем родительский элемент первого неотмеченного чекбокса в переменную parentDiv parentDiv.classList.add('padding'); // добавляем класс padding к родительскому элементу первого неотмеченного чекбокса parentDiv.scrollIntoView({ behavior: 'smooth' }); /* $('html, body').animate({ // анимация прокрутки страницы к родительскому элементу первого неотмеченного чекбокса scrollTop: $(parentDiv).offset().top }, 500);*/ } }); var radioButtons = document.querySelectorAll('.check'); radioButtons.forEach(function (radioButton) { radioButton.addEventListener('click', function () { // при клике на любую чекбокс кнопку var parentDiv = this.parentElement; // сохраняем родительский элемент чекбокса в переменную parentDiv parentDiv.classList.remove('padding'); // удаляем класс padding у родительского элемента этой чекбокс кнопки }); }); </script> </body> </html> Зачем jquery, да еще две штуки? scrollIntoView прекрасно работает. |
Цитата:
Читал что только файр фоксе она работает. |
voraa,
Спасибо |
Вот даже тут в коде нету плавной анимации, я сижу с яндекс браузера
|
В хроме, ейдже, файрфоксе работает. Сафари у меня нет - проверить не могу.
|
Часовой пояс GMT +3, время: 16:10. |