Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   jquery -> js (https://javascript.ru/forum/misc/73859-jquery-js.html)

SpaceAlarm 22.05.2018 21:41

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
		});
});

рони 22.05.2018 21:57

SpaceAlarm,
4
http://javascript.ru/forum/misc/4281...da-v-pole.html

j0hnik 23.05.2018 06:03

Цитата:

Сообщение от SpaceAlarm
$('input[name=options]:checked', '#form').val();

мб так?

$('input[name=options]:checked, #form').val();

ksa 23.05.2018 08:50

Цитата:

Сообщение от SpaceAlarm
$('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>

ksa 23.05.2018 08:55

Цитата:

Сообщение от j0hnik
мб так?

$('input[name=options]:checked, #form').val();

Это вот так
$('#form input[name=options]:checked').val();

Nexus 23.05.2018 09:22

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);
    });
});

SpaceAlarm 23.05.2018 14:23

Спасибо большое!

SpaceAlarm 23.05.2018 16:13

а 2? как будет

Nexus 23.05.2018 16:18

SpaceAlarm, соберите его самостоятельно из 1 и 3.

SpaceAlarm 23.05.2018 16:21

Цитата:

Сообщение от Nexus (Сообщение 485845)
3.
document.addEventListener('DOMContentLoaded', function() {
    const listener = function() {
        console.log(this.value || '');
    };

    const node = document.getElementBuId('name_button');
    if (!node)
        throw new Error('Element not found');

    ['change', 'input'].forEach(function(event) {
        node.addEventListener(event, listener);
    });
});

не работает что то, не пишет текст в консоль https://jsfiddle.net/d4n2szc5/1/
Вот так должно быть https://jsfiddle.net/qLaaa0dd/

Nexus 23.05.2018 16:26

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'));

рони 23.05.2018 21:01

4.
https://developer.mozilla.org/ru/doc...ement/datalist
html-datalist-values-from-array-in-javascript

Malleys 24.05.2018 03:54

<!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.