@ended

Как каждый раз записывать значение переменной новый div?

Только только изучил немного верстки, перешел на js. Изучаю по халявно скачанным курсам скиллбокс (не реклама). Есть задание со списком дел, в 2 поля вводишь название и описание, затем "дело" появляется в другой колонке, где его можно удалить.

Проблема в том, что при создании 2ого "дела", ззначения переменных заменяются в первом, а не записываются в новый блок.

<!DOCTYPE html>
<html lang="ru">
<head>
	<title>Список дел</title>
	<link rel="stylesheet" type="text/css" href="styles.css">
	<script src="jquery-3.5.1.min.js"></script>
	<script src="script.js"></script>
</head>
<header>

</header>
<body>
	<div class="fixed-container">
		<section id="column-left">
			<h2>Список дел:</h2>
<!-- 					<div id="list-clear">Список пуст...</div> -->
		</section>
			<section id="column-right">
			<h2>Добавить новое дело:</h2>
				<aside id="instruction-desc">
					<div class="description">
						<div class="text-desc">* Название</div>
						<input type="text" name="name-instr" minlength="3" maxlength="30" id="i-name">
					</div>
					<div class="description">
						<div class="text-desc">* Описание</div>
						<textarea minlength="3" maxlength="774" id="i-desc"></textarea>	
					</div>
					<button id="add-instr">Добавить дело</button>
				</aside>
			</section>
		</div>
</body>
</html>


html, body {
	margin: 0;
	padding: 0;
	min-width: 1000px;
	font-family: Arial;
}

body {
	background-color: #f5f5f5;
}

h2 {
	margin: 0;
}

.fixed-container {
	width: 960px;
	margin: 60px auto ;
	position: relative;

}

#column-left {
	float: left;
	width: 470px;
}

#column-right {
	float: right;
	width: 470px;
	margin-bottom: 150px;
}

#list-clear {
	font-size: 14px;
	color: #8993ad;
	margin: -50px 0;
	visibility: visible;
}

.instruction {
	width: 470px;
	height: 140px;
	background-color: white;
	margin-top: 30px;
	position: relative;
}

#iname{
	width: 450px;
	padding: 15px 0 15px 20px;
	float: left;
	color: black;
	font-size: 16px;
	font-weight: bold;
	border-bottom: 1px solid #e5e5e5;
}

#idesc {
	width: 450px;
	padding: 55px 0 0px 20px;

}

#close-instr {
	background-color: white;
	border: 0;
	outline: none;
	padding: 0;
	margin-left: 10px;
	position: absolute;
}

#instruction-desc {
	background-color: white;
	margin-top: 30px;
	width: 470px;
	height: 500px;
}

.text-desc {
	font-size: 14px;
	color: #8993ad;
}

.description {
	margin: 0 40px;
	padding-top: 30px;
}

	.description input {
		width: 390px;
		height: 43px;
		margin-top: 10px;
		padding: 0 0 0 10px;
		border: 1px solid #ebebeb;
		outline: none;
	}

	.description textarea {
		width: 390px;
		height: 218px;
		margin: 10px 0 30px 0;
		padding: 10px 0 0 10px;
		border: 1px solid #ebebeb;
		outline: none;
		display: block;
		resize: none;
	}

#add-instr {
	width: 225px;
	height: 55px;
	margin-bottom: 35px;
	margin-left: 40px;
	border: 0;
	background-color: #2174fd;
	color: white;
	font-size: 16px;
}


$(function(){

	$('#add-instr')
		.click(function (){

			$('#column-left')

			.append('<article class="instruction"><div id="iname"></div><div id="idesc"><div class="text-desc"></div></div></article>');
			
			document.querySelector('#iname').innerHTML = document.querySelector('#i-name').value + ('<button id="close-instr"><img alt="Close" src="img/clear-button.png"></button>');

			document.querySelector('#idesc').innerHTML = document.querySelector('#i-desc').value;

		})



	$('#column-left').on('click', '#close-instr', function() {
		$('.instruction').remove();
	});

});


Еще стоит вопрос с удалением конкретного дела. Спасибо за помощь, я тут первый раз:)
  • Вопрос задан
  • 198 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
А вот балбесы вроде вас:

Почему данный Juqery скрипт прячет только один div,а не два?
Как применить функцию ко всем одинаковым id?
Как получить индекс элемента id из дива формы?
Добавить и удалить элемент на JS/jQuery?
Как сделать одинаковые якорные ссылки для сайта с разной версткой под моб и декстоп?
Как сделать клик по элементу?
Почему меняет класс только у первого элемента?
Почему jquery replaceWith работает только с одним div?
Как нажать на все кнопки одновременно по ID кнопки?
Как подставить ссылку для iframe, используя данные полей ввода html?
Почему addclass добавляется только первому элементу в списке?

Попробуйте найти что-то общее.

Если не сможете, жмите сюда (нет, никаких объяснений не будет - они по ссылкам выше, здесь только код).
$('#add-instr').click(function() {
  $('#column-left').append(`
    <article class="instruction">
      <div class="name">
        ${$('#i-name').val()}
        <button class="remove">x</button>
      </div>
      <div class="desc">
        ${$('#i-desc').val()}
      </div>
    </article>
  `);
});

$('#column-left').on('click', '.remove', function() {
  $(this).closest('.instruction').remove();
});
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы