I am developing a web application in Go. I have a drop-down list, it is formed from a template.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn"> Удалить услугу</button>
<ul id="myDropdown" class="dropdown-content">
{{range .}}
<li>{{.Id}}</li>
{{end}}
</ul>
</div>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
The logic of the operation is as follows: the user selects a list item -> the selected value must be transmitted to the server to execute further instructions.
Understanding this problem, I tried to first output the data to the console in the browser:
var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
var targetEl = event.target;
console.log(targetEl.innerHTML)});
I did it, but I have no idea what to do next. The server code is represented below:
func main() {
r := httprouter.New()
routes(r)
err := http.ListenAndServe("localhost:4444", r)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
}
func routes(r *httprouter.Router) {
r.ServeFiles("/public/*filepath", http.Dir("public"))
r.GET("/", controller.StartPage)
r.GET("/auth", controller.LoginPage)
r.POST("/login", controller.Log_in)
r.POST("/add_uslugu", controller.Add_from_html)
}
You can send an AJAX request. In the code chunk below I'm getting the li
elements (not the ul
as you did) and add a click listener to each of them, I mine the id
as the innerText
of the li
and then sending an AJAX request, passing the id
. I'm not aware of the path where this needs to be sent, so you will need to replace the path with your own and I'm also unsure what type of request you need, I was doing a POST request. Finally, I created a callback function for you that currently does nothing, but you will need it to handle server responses.
var ul = document.querySelectorAll('ul > li');
for (let li of ul) {
li.addEventListener('click', function (event) {
let id = li.innerText;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Do something with this.responseText;
}
};
xhttp.open("POST", "<yoururl>", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id=" + id);
}
}