<div >
<div >
<a href="/addcourse">
<button >add course</button>
</a>
<div >
<h1>manage courses</h1>
</div>
<div style="padding-left: 500px">
<form style="width: 50%;">
<div >
<label for="faculty" ></label>
<div >
<div >
<button index=0 id='facultyDropdown' >Faculties</button>
<button data-toggle="dropdown">
<span ></span>
</button>
<ul >
{{#facultyId}}
<li><a index="{{id}}">{{faculty}}</a></li>
{{/facultyId}}
</ul>
</div>
</div>
</div>
<div >
<div >
<input id="submit" name="submit" type="bottom" value="submit" >
<table >
<thead>
<tr>
<th scope="col1" >corse code</th>
<th scope="col1" >course name</th>
<th scope="col2">credit hourse</th>
<th scope="col5"></th>
<th scope="col6"></th>
</tr >
<tbody id="myTable"></tbody>
</thead>
</table>
</div>
</div>
</form>
</div>
This HTML page has 2 main buttons and I generated two more buttons in every table row. The two buttons in the row don't work with ajax.
$(document).ready(function(){
function buildTable(data){
document.getElementById('myTable').innerHTML = "";
var table = document.getElementById('myTable');
for (var i = 0; i < data.length; i ){
var row = `<tr>
<td>${data[i].code}</td>
<td>${data[i].course}</td>
<td>${data[i].id}</td>
<td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" >update</button></td>
<td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" >delete</button></td>
</tr>`
table.innerHTML = row
}
}
$(".dropdown-menu li a").click(function(){
const index = $(this).attr('index');
$("#facultyDropdown").attr('index', index);
$("#facultyDropdown").text($(this).text());
});
$("#submit").click(function() {
console.log('alaa');
const facultyId = $("#facultyDropdown").attr('index');
$.ajax({
type: "post",
url: `/api/v1/faculties/` `${facultyId}`,
success:function(res){
courses= res
buildTable(courses)
console.log('courses')
}
});
});
$(".delete").click(function() {
const corseid = $(this).attr("id");
console.log(corseid);
$.ajax({
type: "delete",
url: `/api/v1/courses/` `${corseid}`,
success:function(res){
alert(`course deleted ${res}`)
}
});
});
$(".update").click(function() {
const corseid = $(this).attr("id");
console.log(corseid);
$.ajax({
type: "put",
url: `/api/v1/courses/` `${corseid}`,
success:function(res){
alert(`course deleted ${res}`)
}
});
});
});
This is the ajax code above, I don't understand that the droplist and the add course button and submit button is working only the update and delete buttons are not working.
CodePudding user response:
The problem is when you create your event handler, the elements don't exist (since they only exist after clicking submit
).
You need to use event delegation, there are a few ways of doing that, this is probably the easiest:
$("#myTable").on("click", ".delete", function (event) {
// your delete code
});