why, by clicking on the span
, its text is not thrown into the input
?
html
JavaScript
x
34
34
1
<script>
2
$(document).ready(function () {
3
$('#ajax-service').keyup(function () {
4
$.ajax({
5
data: $(this).serialize(),
6
url: "{% url 'ajax_request' %}",
7
success: function (response) {
8
if (response.is_exist == true) {
9
let list = ''
10
for (var i in response.is_taken) {
11
list = list + '<span name="'+(response.is_taken[i])+'" id="#service'+(i)+'">'+(response.is_taken[i])+'</span> '
12
}
13
let elem_input = document.querySelector("#ajax-service")
14
let elem = document.querySelector("#service"+i);
15
$('#ajax-service-list').remove();
16
$('#ajax-service').after('<div id="ajax-service-list" name="ajax-service-list">'+(list)+'</div>')
17
elem.addEventListener("click", function(e){
18
elem_input.value = e.target.getAttribute("name");
19
});
20
}
21
else {
22
$('#ajax-service-list').remove();
23
$('#ajax-service').after('<div id="ajax-service-list" name="ajax-service-list"><span class="badge rounded-pill bg-warning text-dark" id="ajax-service-list">Нет совпадений</span></div>')
24
}
25
},
26
error: function (response) {
27
console.log(response.responseJSON.errors)
28
}
29
});
30
return false;
31
});
32
})
33
</script>
34
error in devtools:
JavaScript
1
7
1
?category=simple:151 Uncaught TypeError: Cannot read property 'addEventListener' of null
2
at Object.success (?category=simple:151)
3
at c (jquery-3.6.0.min.js:2)
4
at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2)
5
at l (jquery-3.6.0.min.js:2)
6
at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2)
7
what is wrong with addEventListener?
Advertisement
Answer
There are several problems with the approach.
- You have a loop with multiple
i
values and only use value of the last one after loop completes - Trying to use
querySelector()
before the html string is inserted in document - Using # in the element
id="#service
A better approach would be to use a common class name and event delegation instead.
JavaScript
1
2
1
'<span class="service-list-item">'+(response.is_taken[i])+'</span>';
2
Then outside of the $('#ajax-service').keyup..
do:
JavaScript
1
4
1
$(document).on('click', '.service-list-item', function(e){
2
$('#ajax-service').val( $(this).text());
3
});
4