JS HTML: Get particular column value after button click - javascript

I have a table with several columns. Each row has an edit button.
If the user clicks on it, a modal view opens. The user can enter some values and send these via AJAX to my controller.
My problem is that I have no idea how to transfer to my JS function which particular edit button the user has actually clicked in the table.
In the past I had an edit button in each row:
<td><a th:href="'/edit/' + *{person.getName()}" class="btn-sm btn-success"
role="button">Edit</a></td>
But this led me to a new HTML view where the user could edit. With my new UI I want really only to go with the modal.
But since JS/AJAX has no idea about the whole table it seems to me like a totally wrong approach to me. Moreover I am pretty new to JS/AJAX
Currently I call the JS function like this:
<button type="button" class="btn btn-primary"
id="subscribe-email-form" onclick="updateModal()">Save
</button>
What can solve my Problem?:
If I could just give a parameter to updateModal it would work but since I call the modal view with id="myModal" by the edit button with data-target="#myModal" I cannot transfer any id.
Here is my JS and what I want is to find the correct parameter for the field oldID
Thank you a lot in advance!
function updateModal() {
var newValues = {};
newValues["newName"] = $("#newName").val();
newValues["newAge"] = $("#newAge").val();
newValues["newID"] = $("#newID").val();
var oldID = "???";
$.ajax({
type: "POST",
contentType: "application/json",
url: "/api/edit/oldID",
data: JSON.stringify(newValues),
dataType: 'json',
timeout: 100000,
success: function (data) {
console.log("SUCCESS: ", data);
display("SUCCESS");
resultObj = data.result;
updateContent(resultObj[0].phone);
},
error: function (e) {
console.log("ERROR: ", e);
display("ERROR");
//display(2);
},
done: function (e) {
console.log("DONE");
display("DONE");
enableSearchButton(true);
}
});
}
and the relevant HTML part
<div class="container">
<br>
<h3>Overview</h3>
<br>
<div class="container" id="modal-submit">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">ID</th>
</tr>
</thead>
<tbody>
<!--/*#thymesVar id="productList" type="java.util.List"*/-->
<tr id="person" th:each="person : ${elementList}">
<td th:text="${person.getName()}" id="username"></td>
<!--/*#thymesVar id="getTradableBTC" type="java.lang.Double"*/-->
<td th:text="${person.getAge()}" th:id="${person.getName()+person.getAge()}" id="age"></td>
<!--/*#thymesVar id="getTop" type="java.lang.Double"*/-->
<td th:text="${person.getId()} " th:id="${person.getName()+person.getId()}" id="userID"></td>
<td>
<div class="btn-toolbar" role="toolbar">
<!-- Button trigger modal -->
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal"
data-target="#myModal">
Edit
</button>
</div>
<div class="btn-group mr-2" role="group" aria-label="Second group">
<button type="button" class="btn btn-outline-danger btn-sm" id="delete">Delete
</button>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-primary" type="button" id="addElement">Add Element</button>
<button class="btn btn-light" type="button" id="DeleteAll">Delete all Elements</button>
</div>
</div>
<br>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Change data</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="row">
<div class="col-sm-6">
<div class="modal-body">
<input name="referencia" id="newName" type="text"
class="form-control"
placeholder="Enter new name">
<br>
<input name="referencia" id="newAge" type="text"
class="form-control"
placeholder="Enter new age">
<br>
<input name="referencia" id="newID" type="text"
class="form-control"
placeholder="Enter new id">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Discard
</button>
<button type="button" class="btn btn-primary"
id="subscribe-email-form" onclick="updateModal()">Save
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<br>

1st: id= must be unique so don't duplicate ids .. person1 , age1 , userID1 for the next person 1 will be 2 and so on.. you can also use class= instead of id=
2nd: If change it to classes .. on edit button click you can use
alert($(this).closest('tr').find('.userID').text());
You can then pass the userID to the modal and get it again when saveEdit
Note: This code'll work if you change id="person" to class="person" same thing with age and userID
Again and Again Don't use same id for more than one element .. delete button has duplicated id .. so you need to change it as well .. and after change id="delete" to class="delete" you can then use
$('.delete').on('click' , function(){
// do ajax things for remove then
$(this).closest('tr').remove();
});
If you append the rows dynamically you'll need to use
$(document).on( 'click' , '.delete' , function(){ /* code here */ }); // use same way with dynamically created element events

Related

Submit form to add column in table

I have a table like this:
<table id="criteria-table">
<thead>
<tr>
<th rowspan="2" class="text-center align-middle">#</th>
<th rowspan="2" class="text-center align-middle">Employee</th>
<th colspan="3" class="text-center">Order</th>
</tr>
<tr>
<th class="text-center">Priority</th>
<th class="text-center">Criteria</th>
<th class="text-center">Unit</th>
</tr>
</thead>
<tbody>
<tr class="tr_template">
<td class="text-center">1</td>
<td class="text-center">Employee A</td>
<td class="text-center">75%</td>
<td class="text-center">10</td>
<td class="text-center">order</td>
</tr>
</tbody>
</table>
And I have 2 button in the end of this table:
<a class="btn btn-add-criteria btn-sm m-btn--icon color" href="javascript:void(0)">
<i class="la la-plus"></i>ADD CRITERIA
</a>
<a class="btn btn-add-employee btn-sm m-btn--icon color" href="javascript:void(0)">
<i class="la la-plus"></i>ADD EMPLOYEE
</a>
When I click add criteria button, a popup will open to type criteria data and submit:
<div class="modal fade" id="popup-add" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content clear-form">
<!-- Body modal -->
<div class="modal-body">
<!-- Form -->
<form id="frm-add-criteria">
<div class="row">
<div class="col-lg-12">
<div class="m-form__group">
<div class="criteria-content">
<!-- Criteria -->
<div class="row modal-row">
<div class="col-12">
<label class="font-weight-bold">Criteria</label>
<div class="input-group">
<select name="kpi_criteria_id" id="kpi_criteria_id" class="form-control">
<option value="1">Order</option>
<option value="2">Contract</option>
<option value="3">Revenue</option>
</select>
</div>
</div>
</div>
<!-- Priority -->
<div class="row modal-row">
<div class="col-12">
<label class="font-weight-bold">Priority</label>
<div class="input-group">
<input type="text" class="form-control" id="priority" name="priority" placeholder="Input criteria" aria-describedby="basic-addon2">
</div>
</div>
</div>
<!-- Amount -->
<div class="row modal-row">
<div class="col-12">
<label class="font-weight-bold">Amount</label>
<div class="input-group">
<input type="text" class="form-control" id="kpi_value" name="kpi_value" placeholder="Input amount" aria-describedby="basic-addon2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer modal -->
<div class="modal-footer">
<div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit ss--width--100">
<div class="m-form__actions m--align-right">
<button data-dismiss="modal" class="btn btn-metal bold-huy m-btn m-btn--icon m-btn--wide m-btn--md">
<span class="ss--text-btn-mobi">
<i class="la la-arrow-left"></i>
<span>CANCEL</span>
</span>
</button>
<button type="submit" onclick="" id="btn-save-criteria" class="btn btn-success color_button son-mb m-btn m-btn--icon m-btn--wide m-btn--md btn_add_close m--margin-left-10">
<span class="ss--text-btn-mobi">
<i class="la la-check"></i>
<span>SAVE</span>
</span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
After I submit the form in modal, it will add one more column like this for all employee row in table:
Here is my old table:
After submit form modal:
Same like this, when I click add employee, it will show a modal for me to choose employee, then it will insert one more employee row to this table with all criteria I add before.
Here is my JSFiddle to show you what I did.
I really don't know how to do this so forgive me if you feel I just give you about code not solution.
Hope you can give me a good advise to handle this.
Thank you very much!
You can use JS / JQuery DOM manipulation.
here's an example using JQuery and Bootstrap:
Table
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="tableBody">
<tr>
<td>John</td>
<td>Male</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add Person
</button>
I put an id to the table body (tbody) element so I can access it directly from script side using JQuery.
Modal
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Insert Person</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<label>Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="col-md-6">
<label>Gender</label>
<select id="gender" class="form-control">
<option>Choose Gender</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="addPerson()" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I put id on every input for JQuery access. and since we are not to sending it to a database or another http request, there's no need for a form.
The JQuery Script:
<script>
function addPerson() {
var name = $('#name').val();
var gender = $('#gender').val();
var html = '';
html += '<tr>';
html += '<td>' + name + '</td>';
html += '<td>' + gender + '</td>';
html += '</td>';
$('#tableBody').append(html);
$('#name').val('');
$('#gender').val('Choose Gender');
}
</script>
first I make 3 variables to contain empty string, the value of name, and the value of gender. then I make a table row mock up and fill it with the values from name and gender on that empty string variable, after that I add the new data to the table using the $('#tableBody').append(html); command. and then refresh the form using $('#name').val('');and $('#gender').val('Choose Gender');. hit me up if you need more elaboration.

Angular JS - Problem deleting row from table

#AngularJS
I have a table. When I click the DELETE button on any row, the following code always deletes the first one. Where am I wrong? I'll post part of the code
<tr id="riga" ng-repeat='x in cars'>
<td class="dimensione">{{x.id}}</td>
<td class="dimensione">{{x.targaauto}}</td>
<td class="dimensione">{{x.datiintestatario}}</td>
<td class="dimensione">{{x.marca}}</td>
<td><button type="button" class='btn btn-danger btn' data-bs-toggle="modal" data-bs-target="#finestra"> elimina</button></td>
</tr>
<div class="modal fade " id="finestra">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Attenzione</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<h5 class="modal-body">Sei sicuro di voler eliminare questo record?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ng-click='rimuovi($index)' data-bs- dismiss="modal">OK</button>
<button type="submit" class="btn btn-secondary" data-bs-dismiss="modal">ANNULLA</button>
</div>
</div>
</div>
</div>
</table>
</tbody>
<script src="bootstrap.js"></script>
</body>
</html>
Function RIMUOVI
$scope.rimuovi=function($index){
$scope.cars.splice($index, 1)
}
When you press the
<button type="button" class='btn btn-danger btn' data-bs-toggle="modal" data-bs-target="#finestra"> elimina</button>
button, you need to add
ng-click="verifyDelete($index)"
which you will save in your directive/controller. That way, when you ask "Are you sure" from the modal, you have the correct row.
Update ng-click='rimuovi($index)' to ng-click='rimuovi()' and use the value saved from verifyDelete
The problem is that you are trying to access the $index variable outside the ng-repeat block. To fix this you should store it to a variable in your controller when you click delete and then show the modal.
Or you can pass the object and then make a filter on the array, but the tow options require you to store the value to a variable.

How to pass id to asp-route-id on the modal button

I have a problem with my code. I have table with 3 columns: category, subcategories and actions. In third column I keep buttons "Edit" and "Delete". Below part of my code:
<tbody>
#foreach (var category in Model.ToList())
{
<tr>
<td class="hide">#category.Id</td>
<td>#category.Name</td>
<td>
#if (category.Subcategories != null)
{
#foreach (var subcategory in category.Subcategories.ToList())
{
<p>#(subcategory.Id + ". " + #subcategory.Name)</p>
}
}
else
{
<a class="btn btn-primary" style="width:auto"
asp-controller="administrator"
asp-action="CreateSubcategory">
Dodaj podkategorię
</a>
}
</td>
<td>
<a class="btn btn-primary"
asp-controller="administrator"
asp-action="EditCategory"
asp-route-id="#category.Id">
Edytuj
</a>
<button type="button" onclick="getId(this.data-id)" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-id="#category.Id">
Usuń
</button>
</td>
</tr>
}
</tbody>
When button "Usuń" will be clicked I want show modal window. And this is ok:
<div id="myModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Usuwanie kategorii</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Czy na pewno chcesz usunąć kategorię ?</p>
</div>
<div class="modal-footer">
<form method="post">
<button id="modalDeleteButton" type="submit" class="btn btn-primary"
asp-controller="administrator"
asp-action="DeleteCategory">
Usuń
</button>
</form>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
</div>
</div>
</div>
And finally in modal window user have a two choice - close modal window or "Delete" category. In this place I have to know which row was clicked before modal was showing. How to pass #category.Id to my modal window button "Usuń" and set asp-route-id?
Below my JS/JQuery code:
<script type="text/javascript">
$("#myModal").on('show.bs.modal', function (event) {
$(event.currentTarget).find('asp-route-id').val(getId);
});
function getId(clicked_id) {
return clicked_id;
}
Now I have got return url https://localhost:80888/Administrator/DeleteCategory - without "/7" where 7 is Id.
In <tbody>, the id of this fragment should be sent by #category.Id.
<tbody>
...
<button type="button" onclick="getId(#category.Id)" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-id="#category.Id">
Usuń
</button>
</td>
</tr>
}
</tbody>
In the js function, the call of the getId function needs to allocate parameters, so it cannot be called directly to get its value. First, set a global variable. Then, since the browser has compiled taghelper into formaction when calling modal, this value needs to be reset here.
<script type="text/javascript">
var clickId;
$("#myModal").on('show.bs.modal', function (event) {
$(event.currentTarget).find('asp-route-id').val(getId);
var btn = $(this).find('#modalDeleteButton');
console.log(clickId)
btn.attr('formaction', '/administrator/DeleteCategory/'+clickId);
});
function getId(clicked_id) {
this.clickId = clicked_id;
}
</script>
Codes of Controller
public class administratorController:Controller
{
public IActionResult DeleteCategory(int id)
{
return Json(id);
}
}
Screenshots of Test

JavaScript Passing Parameters to modal ASP.NET Core

I have problem with my modal boostrap seems like not passing parameter to modal. Here is my code:
My view:
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.EmployeeId)</td>
<td>#Html.DisplayFor(modelItem => item.Fname) #Html.DisplayFor(modelItem => item.Lname)</td>
<td>#Html.DisplayFor(modelItem => item.PhoneNumber)</td>
<td>#Html.DisplayFor(modelItem => item.Position)</td>
<td>
<a asp-action="Edit" asp-route-id="#item.EmployeeId">Edit</a> |
<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal" data-emp-id="#item.EmployeeId"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
</td>
</tr>
}
My modal:
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete invoice number:</p>
<input type="text" name="empID" value=""/>
</div>
<div class="modal-footer">
<form asp-controller="Employee" asp-action="Delete" method="post" class="form-inline" role="form">
<input type="hidden" id="Id">
<button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
My JavaScript:
I think the problem is somewhere in this code but I don't know why.
<script src="./javascript.js" type="text/javascript">
$("button[type='button']").click(function () {
$("#myModal").find("input[type='text']").val($(this).attr("EmpID"));
});
What makes it wrong with my work? Does anyone knows why is not passing the parameter to model?
I'm just a beginner and I have no idea whats going on in my codes.
Any help would be appreciated.
Your button doesn't have an attribute named EmpId. However it does have an attribute named data-emp-id which I assume contains the value you want.
jQuery has a data method for accessing data attributes easily; in short you can get it using $(this).data("emp-id")

How to get values on click from table row and show it in input fields

Here I have a gviz table with data: http://jsbin.com/OJAnaji/9 and CODE: http://jsbin.com/OJAnaji/9/edit
I also create an modal window with input fields. Now I want when I click on table row to show row data into input fields in modal window... How I can do that?
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Edit selected row</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
<div class="input-group">
<span class="input-group-addon">Name</span>
<input type="text" id-"name" class="form-control" placeholder="Type name">
</div></br>
<div class="input-group">
<span class="input-group-addon">Gender</span>
<input type="text" id="gender" class="form-control" placeholder="Gender?">
</div></br>
<div class="input-group">
<span class="input-group-addon">Age</span>
<input type="text" id="age" class="form-control" placeholder="Number of age">
</div></br>
<div class="input-group">
<span class="input-group-addon">Donuts eaten</span>
<input type="text" id="donuts_eaten" class="form-control" placeholder="Number of donuts eaten">
</div></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
So:
1.user click on table row
2.user click on button "Edit row"
3.User get values from row to input fields
Is this possible to do ?
sorry for my english its bad but i'm learning hard
Check this fiddle, this is partially working i.e. only for table rows with white background. Change necessary things to get it worked for all rows.
because im not familiar with the code of yours i will write a code i think will suit you and add some comments to make it more clear and you tell me if you need something else.
$("#YourTableId tbody tr").click(function () {
//this = the row a user has clicked
var storedNameInTable = $(this).find("#name").text(); // will get the label with id = name from the same row a user has clicked
$("#name").val(storedNameInTable); //will take the name and put it on the textbox.
var self = this; //saves the row scope
$("#SaveChanges").click(function () {
var NameAfterChange = $("#name").val(); //takes the newly changed name
$(self).find("#name").text(NameAfterChange); //puts it in the table
$("#SaveChanges").unbind("click"); //make sure you want call this button again so you want have more than 1 click event
});
});

Categories