jquery -> js
Добрый вечер, как переписать данный код с jquery на чистый js?
1. $('input[name=options]:checked', '#form').val(); 2. $('#form input').on('change', function() { let Button = $('input[name=options]:checked', '#form').val(); }); 3. $(document).ready(function() { $("#name_button").bind("change input", function() { let getInput = $("#name_button").val(); console.log(getInput); }); }); 4. let getURLmessage = [ "test", "test1", "test2", "test3" ] $(function() { $("#name_button").autocomplete({ source: getURLmessage }); }); |
|
Цитата:
$('input[name=options]:checked, #form').val(); |
Цитата:
<form id='form'> <input type='checkbox' name='options' value='test' checked /> </form> <script type='text/javascript'> var o=document.querySelector('#form input[name=options]:checked'); var val=(o)? o.value: ''; alert(val) </script> |
Цитата:
$('#form input[name=options]:checked').val(); |
3.
document.addEventListener('DOMContentLoaded', function() { const listener = function() { console.log(this.value || ''); }; const node = document.getElementById('name_button'); if (!node) throw new Error('Element not found'); ['change', 'input'].forEach(function(event) { node.addEventListener(event, listener); }); }); |
Спасибо большое!
|
а 2? как будет
|
SpaceAlarm, соберите его самостоятельно из 1 и 3.
|
Цитата:
Вот так должно быть https://jsfiddle.net/qLaaa0dd/ |
SpaceAlarm,
2. document.addEventListener('DOMContentLoaded', function() { const listener = function() { let Button = document.querySelector('#form input[name="options"]:checked').value || null; }; [].forEach.call(document.querySelectorAll('#form input'), function(node) { ['change', 'input'].forEach(function(event) { node.addEventListener(event, listener); }); }); }); Пост №6 поправил, опечатался. После моих скриптов добавьте этот скрипт и все заработает: if (document.readyState === 'complete') document.dispatchEvent(new Event('DOMContentLoaded')); |
|
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> </head> <body> <form id="form"> <input type="text" id="name_button" list="name-button-list"> <datalist id="name-button-list"></datalist> <input type="checkbox" name="options" checked> <input type="checkbox" name="options"> <input type="checkbox" name="options"> </form> <script> // Вспомогательные функции, которые помогают // найти элемент(-ы) по указанному селектору // в контексте какого-либо элемента function $(selector, context = document) { return context.querySelector(selector); } function $$(selector, context = document) { return context.querySelectorAll(selector); } // 1 for(const element of $$("#form input[name=options]:checked")) { element.value; } // 2 document.addEventListener("change", ({ target }) => { if(!target.matches("#form input[name=options]:checked")) return; /*const Button = */target.value; // значение конкретно того элемента, что поменяли }); // 3. Обычно не нужно прослушивать событие change, // когда прослушиваете input. // Обратите внимание, что у строки "name_button", нет спереди // символа «решётка», поскольку id возвращает само имя // идентификатора элемента. document.addEventListener("DOMContentLoaded", () => { document.addEventListener("input", ({ target }) => { if(target.id !== "name_button") return; const getInput = target.value; console.log(getInput); }); }); // 4 const getURLmessage = [ "test", "test1", "test2", "test3" ]; $("#name_button").list.append(...getURLmessage.map(m => new Option(m))); </script> </body> </html> |
Часовой пояс GMT +3, время: 11:57. |