У меня есть веб-сайт, и я пытаюсь сделать так, чтобы был список кнопок, и когда вы нажимаете на элемент списка, он заполняет некоторые текстовые поля внизу данными из объекта, но когда я нажимаю на него, он заполняет текстовое поле с неверными данными.
{% extends "base.html" %} {% block title %}Records{% endblock %}
{% block content %}
<div style = "background-color:lightgrey">
<br/>
<h1 align = "center">Add Record</h1>
<br/>
<br/>
<script>
function myFunction() {
// Get the checkbox
var checkBox = document.getElementById("check");
// Get the output text
var text = document.getElementById("ex");
var date = document.getElementById("dtr");
var datetxt = document.getElementById("datetxt");
// If the checkbox is checked, display the output text
if (checkBox.checked == true) {
text.hidden = false;
datetxt.hidden = true;
date.hidden = false;
} else {
text.hidden = true;
datetxt.hidden = false;
date.hidden = true;
}
}
function edit(noteid, ndate, ncid, nhours) {
// Get the output text
var day = document.getElementById("editday");
var num = document.getElementById("editnum");
var cid = document.getElementById("caid");
var nid = document.getElementById("naid");
day.value = ndate;
num.value = nhours;
cid.value = ncid;
nid.value = noteid;
}
</script>
<form id = "clock" method = "POST" align = "center">
<label style = "font-family:arial" id = "datetxt" name = "datetxt">{{ day }}</label>
<input type = "checkbox" name = "check" id = "check" onclick = "myFunction()">
<div id = "dtr" name = "dtr" hidden>
<label>Date:</label>
<input type = "date" style = "font-family:arial" id = "date" name = "date" value = "{{day}}">
</div>
<br/>
<label for = "hours" style = "font-family:arial">Hours Worked: </label>
<input type = "number" step = "0.1" name = "hours" id = "hours">
<br/>
<label for = "id">Charge Code:</label>
<select name = "id" id = "id">
{% for cont in contracts %}
<option>
{{ cont.name }}
</option>
{% endfor %}
</select>
<br/>
<div name = "ex" id = "ex" hidden>
<label>Explanation:</label>
<input type = "textarea" name = "textar" id = "textar" placeholder = "none">
</div>
<br/><br/>
<div align = "center">
<button type = "button" onclick = "submitForm('/home', 'clock')" class = "btn btn-primary">Clock Time</button>
</div>
<br>
</form>
<hr />
<h4 align = "center">TIMES</h4>
<div style = "width:auto; height:350px; overflow-y:scroll; background-color:grey;" align = "center">
{% for note in notes %}
{% if not note.isquery %}
{% if note.locked %}
<form id = "edit{{ note.id }}" method = "POST">
<input type = "date" name = "day{{ note.id }}" id = "day{{ note.id }}" value = "{{ note.date }}" disabled>
<input type = "text" step = "0.1" value = "{{ note.hours }} (LOCKED)" id = "num{{ note.id }}" name = "num{{ note.id }}" disabled>
<select name = "cid{{ note.id }}" id = "cid{{ note.id }}" disabled>
{% for item in contracts %}
{% if item.cid == note.mins %}
<option class = "list-group-item" selected>{{ item.name }}</option>
{% else %}
<option class = "list-group-item">{{ item.name }}</option>
{% endif %}
{% endfor %}
</select>
{% else %}
<form id = "edit{{ note.id }}" method = "POST">
<button type = "button" onclick = "edit({{ note.id }},{{ note.date }},{{ note.mins }},{{ note.hours }})" style = "background-color:grey;border: 2px solid grey;">
<input type = "date" name = "day{{ note.id }}" id = "day{{ note.id }}" value = "{{ note.date }}" disabled>
<input type = "number" step = "0.1" value = "{{ note.hours }}" id = "num{{ note.id }}" name = "num{{ note.id }}" disabled>
<select name = "cid{{ note.id }}" id = "cid{{ note.id }}" disabled>
{% for item in contracts %}
{% if item.cid == note.mins %}
<option class = "list-group-item" selected>{{ item.name }}</option>
{% else %}
<option class = "list-group-item">{{ item.name }}</option>
{% endif %}
{% endfor %}
</select>
<!--
<input type = "text" minlength = "30" maxlength = "60" placeholder = "Provide Reason For Edit" id = "exp{{ note.id }}" name = "exp{{ note.id }}">
<button type = "button" onclick = "submitForm('/edit-note', 'edit{{ note.id }}')" class = "btn btn-success">Submit Changes</button>
<button type = "button" onclick = "submitForm('/delete-note', 'edit{{ note.id }}')" class = "btn btn-danger">Delete</button>
</form>-->
{% endif %}
<input type = "hidden" name = "nid" value = "{{ note.id }}">
</button>
</form>
</br>
{% endif %}
{% endfor %}
</div>
<br>
<div align = "center">
<h3>Edit</h3>
<form id = "editing" method = "POST">
<input type = "text" name = "editday" id = "editday" value = "">
<input type = "number" step = "0.1" value = "" id = "editnum" name = "editnum">
<input type = "hidden" name = "caid" id = "caid" value = "">
<input type = "hidden" name = "naid" id = "naid" value = "">
</form>
</div>
<br>
<br>
</div>
{% endblock %}
</pre>
в результате в текстовом поле Editday внизу была указана дата, которой не было в note.date, оно вывело «2014», хотя должно было быть 24.06.2024.
Добавьте тег используемой вами структуры шаблона, который определяет все элементы {}.
как мне использовать визуализированный HTML, это мой первый пост.
Используйте инспектор DOM, чтобы убедиться, что аргументы в каждом элементе соответствуют вашим ожиданиям.
Используйте View Source в браузере, чтобы увидеть отрендеренный HTML.
все в порядке, пока я не запустил функцию JavaScript edit(), нажав кнопку списка, но я не вижу, что произойдет после этого в инспекторе. Спасибо, я бы не подумал использовать источник представления в браузере.
Проблема, должно быть, в том, что ваш цикл вводит неправильные значения edit({{ note.id }},{{ note.date }},{{ note.mins }},{{ note.hours }}). Вы сможете увидеть это в View Source.
все заполнено правильно, кроме даты. он хранится в формате «ГГГГ-мм-дд»
Является ли формат даты причиной ошибки? Возможно, вам просто нужно отформатировать дату при передаче ее в JS.
Мы не так «РЕШИЛИ» в заголовке здесь. Если вы нашли свой ответ, вы можете опубликовать и принять его или удалить вопрос.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


РЕШЕНО: когда он установил:
<button type = "button" onclick = "edit({{ note.id }},{{ note.date }},{{ note.mins }},{{ note.hours }})" style = "background-color:grey;border: 2px solid grey;">
В качестве письменного ввода использовалась {{note.date}}, поэтому прошло 24 июня 2024 г., поэтому они вычитали их друг из друга, решением было добавление переменных в кавычки и переключение кавычек для апострофов:
<button type = "button" onclick='edit({{ note.id }},"{{ note.date }}",{{ note.mins }},{{ note.hours }})' style = "background-color:grey;border: 2px solid grey;">
Пожалуйста, отредактируйте свой код, чтобы использовать визуализированный HTML-код, чтобы мы могли попытаться его отладить.