Hi I am new to ajax and I have a json response from django with a list of names to be displayed as a list of buttons. I want to disable the button once it is clicked.
Below is the html code I currently write, the button display successfully but it does not do the disable button action.
I would also like to ask what is the scope of this onclick
function? Does the function dies at the end of the curly bracket }
? Or does this function check even it is out of scope?
<h3>User List:</h3>
<ul id="userLists"> </ul>
$(document).ready(function(){
$.ajax({
type:"GET",
// getUserList is a django views where it query the database and returns JsonResponse of the user's name
url: "{% url 'getUserList' %}",
success: function(response){
$("#userLists").empty();
// Create a list according to number of users in json
for (var key in response.users){
var temp="<button type=\"button\", name=\"" response.users[key].user "\", class=\"btn btn-outline-danger\">" response.users[key].user "</button>";
$("#userLists").append(temp);
// Here I want to do when clicked, it disables the button and leave others as is.
// Current implementation does not work...
document.getElementsByName(response.users[key].user).onclick =
function(){document.getElementsByName(response.users[key].user).prop('disabled', true)};
};
}
});
})
I have also tried the following implementation, it does not work...
if(document.getElementsByName(response.user[key].user).clicked == true){
document.getElementsByName(response.user[key].user).prop("disabled", true);
};
Thanks all.
CodePudding user response:
getElementsByName returns a node list ... So a collection of matching elements.
That is why .onclick
and .prop("disabled", true)
have no effect.
if response.users[key].user
is to be unique, you can safely use document.getElementsByName(response.user[key].user)[0]
.
So add [0]
to target the first match.
About quotes messing-with, you may be interested in reading about template literals.