Removing item from table with Ajax - javascript

I'm building up a table in the View from clicking items in a dropdown menu; I already have a script that does this.
It is also set up so that when an item in the table is clicked, it is removed by the line $(this).parent().remove();
The above two features work
What I need help with is using Ajax to remove the item from the DB as well as just from the table in the View. I already have the controller set up to do this.
My desire is to pass in the id of a removed row to the Ajax section
//Function to append each item clicked in dropdown box to table
$("#subjectlist")
.change(function () {
$("select option:selected").each(function () {
console.log($("select option:selected"));
//the below line of code is setting the id to the
//string: "this.value" and not the number as desired.
//I have confirmed this.value is a number by console
//logging it
$('#overview').append("<tr id='this.value'><td>" +
$(this).text() + "</td><td id=" + this.value + ">" /*+
"X"*/ + "</td></tr>");
});
})
.trigger("change");
//Function to remove fields from table
$("#overview").on('click', 'td', function () {
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})
//If anyone wants to see ,below is the table and the form tag helper
using mvc core's ajax helpers to add and display items items to the
table with Ajax
<select asp-for="SubjectAreasOfProgramme"
asp-items="Model.SubjectAreasForDropdown"></select>
<table id="overview" class="table table-sm table-borderless">
#foreach (var item in Model.SubjectAreasOfProgramme)
{
<tr><td>#item</td><td id="Remove">X</td></tr>
}
</table>

In your click function you have to get the Id value before sending it the database via ajax.
$("#overview").on('click', 'td', function () {
var item = $(this).parent().find("td").eq(2).html(); // replace 2 with whatever cell that holds id value
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})

Related

binding an id passed through button to data in Jquery

I have a table with rows. In each row is a button that is specific to that row of data through the value of the data's id.
When a button in a specific row is clicked it fires the AJAX function 'options'. If that is successful then I want to append the data from $newElement to the row in which that button is located. The row is not always the same however so I cant just give it a tr#.
In the code below I have the append working with that data I want but it appends it to every row, not limited to the specific row and that button's id. What am I doing wrong?
AJAX/jQuery where I am appending the data from $newElement but am having trouble binding the id from the button. As a result it adds the data from $newElement to every row instead of ONLY the row in which I clicked the button.
function options(id){
jQuery.ajax({
type: 'post',url: my_ajax.ajax_url,
data: {action: 'options_function',cid : id_In},
success: function (data) {
var $id = id
var $newElement=jQuery("<tr>",
{id:'ideal_option'+id,html:data})
jQuery('#list-table tr').append($newElement)}
});
}
The button and its initial table are generated with a combo of jQuery and HTML. This function is launched on page load. :
function Pop(){ ?>
<script>
jQuery('document').ready(function(){
jQuery.ajax({ data: {action: 'list_ct'},
type: 'post', url: my_ajax.ajax_url,dataType: 'JSON', success: function(data) {
var lnth = data.length-1;jQuery.each( data, function( i, val ) {
console.log(val);
jQuery('<tr><td>'+val.Customer_FName+' '+val.Customer_LName+'<br></td><td class="tdid_'+val.id+'">'+val.Status+'</td><td><button id="options" href="javascript:void(0)" class="button" onclick="options('+val.id+')" data-id="'+val.id+'"></button></td></tr>');
});
}
});
});
</script>
<table id='list-header'>
<th>Name</th>
<tbody id='list-table'>
</tbody>
</table>
<?php
}

How to append a link to a table using Javascript?

I have an ajax function that calls a method that returns a JSON file. I want to pull the information from the JSON and append it to the table. Which I can do like this:
function updateHome() {
$.ajax({
type: "POST",
url: '#Url.Action("GetHomePage", "Home")',
dataType: 'json',
success: function (result) {
response = $.parseJSON(result)
$(function () {
$.each(response, function (i, item) {
var table = document.getElementById("deviceTable");
var $tr = $('<tr class="accordion" id="'+item.mac+'">').append(
$('<td>').text(item.name),
$('<td>').text(item.loc),
$('<td>').text(item.com),
$('<td>').text(item.status)
).appendTo(table)
});
});
}
});
}
This works as intended. However, I want to make one of the td a link using <a href= but I'm not sure how I can achieve this using .text(). How can I add different HTML elements to this table?
Thanks!
.text sets the text content of your selection. It protects you from unintentionally injecting HTML.
.html sets the html content of your selection. Use that for a HTML string, or alternatively, use .append:
$('<td/>').append(
$('<a/>', { href: '#', text: 'Anchor text' })
)

Select Row from table with JSON values using JQuery

I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!

On page load call change events?

On page load I need to call change events for the drop down list. Currently what happens is in my Jquery code below when you select a value from the professions drop down list i.e. GP a Help text then below the drop down shows in a DIV area shows, however once you submit the form and if validation is thrown the help text goes from the view.
I need to call change events for the drop down list #profession but not exactly sure how to do this. Please advise
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
{
$('#ProfHelp').html(json.helptext)
$('#ProfHelpAlert').show(); ///////
}
else
$('#ProfHelpAlert').hide(); ///////
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
targetDropdown.change();
}
});
});
Try this:
$(document).ready(function() {
$('#profession').trigger('change');
});

Updating rows that are added dynamically using ajax

I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.

Categories