Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Работа с событием Input. Дублирование div при помощи onclick (https://javascript.ru/forum/events/79244-rabota-s-sobytiem-input-dublirovanie-div-pri-pomoshhi-onclick.html)

Da-bro 14.01.2020 11:20

Работа с событием Input. Дублирование в div при помощи onclick
 
Здравствуйте.
Дано html в котором имеется input (Код напишу ниже). Необходимо сделать скрипт таким образом, чтобы при вводе в input введенные значения дублировались ниже в центр квадрата(то есть в собственный div). Если нажать на этот квадрат, то он удаляется вместе с буквой и из div и из Input. Задачу нужно решить на чистом JS.
Помогите разобраться с темой и решить задачу.
Вот до чего я сам дошел, но код работает не совсем так как надо и не до конца.
Я новичок, не судите строго за код) .

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta name="description" content="">
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<meta name="keywords" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="https://fonts.googleapis.com/css?family=Roboto:100&display=swap" rel="stylesheet">
</head>
<style>
	#fix {
		display: flex; 
		flex-wrap: wrap; 
		width: 100%;
		height: auto;
	}
	.mix{
		color: White;
		background-color: #1C3CE3FF;
		width: 30px;
		height: 30px;
		margin: 5px;
		text-align: center;
		font-size: 24px;
	}
</style>

<title>Алфавит</title>
</head>
<body>
	<div id="fix"></div>
	<input type="text" id="myInput" placeholder="Введите тект" class="Inp" >

	

</body>
<script>
		const inp_var = document.getElementById("myInput")
		inp_var.addEventListener("input", function(e){
			if (event.inputType === "deleteContentBackward") {
				return ;
			};
			const inp_value = inp_var.value;
			console.log(event);
			const para = document.createElement('div');
			para.className = "mix";
			document.getElementById("fix").appendChild(para);
			para.innerHTML = enter_text(inp_value);
			function enter_text (text){
				let end_text = '';
				for (let i = 0; i < text.length ; i++) {
					end_text = text[i];
				}
				return end_text;
			}
			para.onclick = function(q) {
				/*this.hidden=true;*/
				document.getElementById("myInput")
				document.getElementById("fix").removeChild(para);
				inp_var.slice(1, 2);
				console.log(para.id);
			};

			const elementID = document.getElementsByClassName("mix");
			for (let i = 0; i < elementID.length ; i++) {
				elementID[i].id = i;	
			};
		});
</script>
</html>

рони 14.01.2020 11:44

Da-bro,
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta name="description" content="">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="keywords" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100&display=swap" rel="stylesheet">
<style>
    #fix {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: auto;
    }
    .mix{
        color: White;
        background-color: #1C3CE3FF;
        width: 30px;
        height: 30px;
        margin: 5px;
        text-align: center;
        font-size: 24px;
    }
</style>

<title>Алфавит</title>
</head>
<body>
    <div id="fix"></div>
    <input type="text" id="myInput" placeholder="Введите тект" class="Inp" >



</body>
<script>
        const inp_var = document.getElementById("myInput");
        const enter_text = text => [...text].map(a => {
                const para = document.createElement('div');
                para.className = "mix";
                para.textContent = a;
                return para
            })

        const out = _ => {
            const inp_value = inp_var.value;
            fix.textContent = "";
            fix.append(...enter_text(inp_value))
        }
        inp_var.addEventListener("input", out)
        inp_var.addEventListener("keyup", out)

        fix.addEventListener("click", ({target}) => {
        if(target = target.closest(".mix")) {
            target.remove();
            inp_var.value = fix.textContent;
            out()
        }
        })

</script>
</html>

Malleys 14.01.2020 11:52

Цитата:

Сообщение от Da-bro
Если нажать на этот квадрат, то он удаляется вместе с буквой и из div и из Input.
Помогите разобраться с темой и решить задачу.

Например, так...
<!DOCTYPE html>
<html>
<head>
	<title>Алфавит</title>
	<meta charset="utf-8">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="https://fonts.googleapis.com/css?family=Roboto:300&display=swap" rel="stylesheet">
</head>
<style>
	html {
		font: 1em Roboto, sans-serif;
	}
	input, button {
		font: inherit;
	}
	#fix {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		height: auto;
	}
	.mix {
		border: none;
		color: white;
		background-color: #1C3CE3;
		width: 30px;
		height: 30px;
		margin: 5px;
		text-align: center;
		font-size: 24px;
	}
</style>
</head>
<body>
	<input type="text" id="myInput" placeholder="Введите текст" class="Inp">
	<div id="fix"></div>
</body>
<script>
	const fix = document.getElementById("fix"), myInput = document.getElementById("myInput");
	myInput.addEventListener("input", function(event) {
		const target = event.target;
		fix.textContent = "";
		
		for(const character of target.value) {
			const button = document.createElement("button");
			button.className = "mix";
			button.textContent = character;
			fix.append(button);	
		}
	});
	fix.addEventListener("click", function(event) {
		const target = event.target.closest(".mix");
		if(!target) return;
		target.remove();
		myInput.value = fix.textContent;
	});
</script>
</html>


Цитата:

Сообщение от Da-bro
Я новичок, не судите строго за код)

Используйте вместо <div> — кнопку <button>

Da-bro 14.01.2020 11:59

Спасибо, а можно без стрелочных функций?
И если что можно задать вам вопросы по коду, чтобы разобраться?

Da-bro 14.01.2020 12:02

Цитата:

Сообщение от Malleys (Сообщение 518717)
Например, так...
<!DOCTYPE html>
<html>
<head>
	<title>Алфавит</title>
	<meta charset="utf-8">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="https://fonts.googleapis.com/css?family=Roboto:300&display=swap" rel="stylesheet">
</head>
<style>
	html {
		font: 1em Roboto, sans-serif;
	}
	input, button {
		font: inherit;
	}
	#fix {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		height: auto;
	}
	.mix {
		border: none;
		color: white;
		background-color: #1C3CE3;
		width: 30px;
		height: 30px;
		margin: 5px;
		text-align: center;
		font-size: 24px;
	}
</style>
</head>
<body>
	<input type="text" id="myInput" placeholder="Введите текст" class="Inp">
	<div id="fix"></div>
</body>
<script>
	const fix = document.getElementById("fix"), myInput = document.getElementById("myInput");
	myInput.addEventListener("input", function(event) {
		const target = event.target;
		fix.textContent = "";
		
		for(const character of target.value) {
			const button = document.createElement("button");
			button.className = "mix";
			button.textContent = character;
			fix.append(button);	
		}
	});
	fix.addEventListener("click", function(event) {
		const target = event.target.closest(".mix");
		if(!target) return;
		target.remove();
		myInput.value = fix.textContent;
	});
</script>
</html>


Используйте вместо <div> — кнопку <button>

Malleys,
Спасибо. Буду сейчас разбираться с кодом, если что можно будет обратиться к вам с вопросами?

Malleys 14.01.2020 12:03

Цитата:

Сообщение от Da-bro
Спасибо, а можно без стрелочных функций?

Можно! А что с ними не так?

Цитата:

Сообщение от Da-bro
И если что можно задать вам вопросы по коду, чтобы разобраться?

Да!

Da-bro 14.01.2020 12:10

Цитата:

Сообщение от Malleys
Можно! А что с ними не так?

С ними все хорошо. Это я просто пока не разбирался как они пишутся и соответственно читаются. По рекомендациям, говорят, новичку(мне) лучше писать код полностью, чтобы не запутаться.
Спасибо за помощь, если что вопросы напишу в тему ниже, чтобы если другие с такой же проблемой столкнуться, чтобы понимали как ее решить.


Часовой пояс GMT +3, время: 10:44.