Delete A Record From Dynamic table using javascript - javascript

I have Generated Dynamic Table Using Following Code in C# + Mongodb
for (var i = 0; i < data.length; i++) {
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' id='delete' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord()'></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
Now I Want To delete Record when I click To Delete Button the Following Function Will Execute
function deleteRecord() {
var sid = $("#delete").attr("sid");
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
},
error: function () {
console.log('there is some error');
}
});
}
But The Problem Is That When I Click To Delete Button I get Same Id For Each Record ,So If I Click Any Button Only First Record Will Delete.
Anyone Have Solution?

Id must be unique for each element use class instead of id or simply pass id to the function as below
for (var i = 0; i < data.length; i++) {
var sid = data[i].sid;
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord("+ sid +")'></td>\
<td><input type='button' value='update' sid='" + data[i].sid + "' onclick='updateRecord("+ sid +");'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
and in your update record or delete record function do as below
function deleteRecord(sid) {
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
},
error: function () {
console.log('there is some error');
}
});
}

first, you need to change your function, add 1 argument to your function
function deleteRecord(id) {
then change var sid value to be var sid = id;
With onclick, you can use
onclick="deleteRecord(pass_some_id from data[i].sid)"
Without onclick, var sid = $("#delete").attr("sid"); will choose first sid attribute value from input list, so what you need is
$("#delete").each(function(){
$(this).onclick(function(){
var sid = $(this).attr("sid"); // get attr value from specify clicked button
deleteRecord(sid); // call delete record with specify id
})
})
or simply way :
change
var sid = $("#delete").attr("sid");
to
var sid = $(this).attr("sid"); // select attribute value from current clicked element
Full Example from #lukesUbuntu :
https://jsfiddle.net/mvLwymvb/
here some good reference :
http://api.jquery.com/jquery.each/
https://api.jquery.com/category/selectors/

You can append the value of i with the id and onclick you can pass the context using this
"<tr>" +
"<td>" + data[i].sid + "</td>" +
"<td> " + data[i].fname + " </td>" +
"<td>" + data[i].lname + "</td>" +
"<td>" + data[i].email + "</td>" +
"<td>" + data[i].pass + "</td>" +
"<td>" + data[i].address + "</td>" +
"<td><input type='button' id='delete_'"+i+" value='delete' " +
// ^ changed here
"sid='" + data[i].sid + "' onclick='deleteRecord(this)'></td>" +
"<td><input type='button' id='update_'"+i+" value='update'" +
// ^ Changed here
" sid='" + data[i].sid + "' onclick='updateRecord(this);'></td>" +
"</tr>";
in deleteRecord function
function deleteRecord(elem){
var getId = elem.id // id of the clicked element
}

Working example here https://jsfiddle.net/mvLwymvb/1/
for (var i = 0; i < data.length; i++) {
strData += "<tr>\
<td>" + data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input class='delete' type='button' id='delete' value='delete' sid='" + data[i].sid + "'></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
$(".delete").click(function() {
var sid = $(this).attr("sid");
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function(response) {
alert("you have successfully deleted record");
},
error: function() {
console.log('there is some error');
}
});
})

Finally I Got The Solution
And That Solution is A Deligets
function check()
{
$(document).on('click', '#delete', function (event) {
var element = event.target;
var sid = $(element).attr("sid");
console.log(sid);
deleteRecord(sid);
});
}
function deleteRecord(sid) {
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
} ,
error: function () {
console.log('there is some error');
}
});
This Is Html Part
for (var i = 0; i < data.length; i++) {
var sid = data[i].sid
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' id='delete' value='delete' sid='" + sid + "' onclick='check()' ></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
Thank You so much Every One

Don't mess up with native JavaScript and jQuery. You will confuse later.
First don't do inline onclick when you have jQuery, use $(elem).click(function) instead.
Second id must be unique (1 id must be used by 1 element only), class is general (1 class can be used by many element).
Try to edit this line
...
<td><input type='button' id='delete' value='delete' class="btn-delete" sid='" + data[i].sid + "' ></td>\
...
and your script
<script>
$(function(){
$('body').on('click', '.btn-delete', function(){
var sid = $(this).attr("sid");
var tr = $(this).closest('tr');
//alert(sid);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'Home.aspx/deleteData',
data: {id: sid},
//async: false, why you need to do this????
success: function (response) {
console.log(response);
alert("you have successfully deleted record");
tr.remove();
},
error: function (response) {
console.log('there is some error');
console.log(response);
}
});
})
});
</script>

Related

How to use javescript reduce() Statistics of keywords contained in array members I have a API URL and calculate baseball data, EX. TaggedPitchType

Use the information returned by the API to make a form,
I have a problem with the syntax of statistics, how to use string statistics to turn them into number, and generate a chart table.
enter image description here
enter image description here
<$(document).ready(function () {
/* $("#row").html("<td></td>"); */
$.ajax({
url: 'https://statsinsight-code-interview.herokuapp.com/get/Get_Balls_CI',
type: "get",
dataType: "json",
success: function (info) {
$("#row").html(
"<tr><td>" + info[0].TaggedPitchType + "</td><td>" + info[0].null + "</td></tr>" + info[0].APP_VeloRel + "</td></tr>"
)
console.log(info);
console.log("====================");
console.log(info[3].APP_KZoneY);
console.log(info[3].APP_KZoneZ);
console.log(info[3].TaggedPitchType);
console.log(info[3].APP_VeloRel);
console.log(info[4].Pitch_ID);
console.log(info.length);
total_len = info.length;
for (i = 0; i < total_len; i++) {
$("#row").append(
"<tr>" +
"<td>" + info[i].TaggedPitchType + "</td>" +
"<td>" + info[i].null + "</td>" +`enter code here`
"<td>" + info[i].APP_VeloRel + "</td>" +
"<td>" + info[i].Strikes + "</td>" +
"<td>" + info[i].null + "</td>" +
"</tr>"
/* console.log(info[i].TaggedPitchType); */
)
}
},
error: function (data) {
console.log("failed");
}
});
});
>

Dynamically number of buttons after ajax call

I have to dynamically create buttons in an Ajax success function. There isn't a fixed number of buttons and
each time the number is different.
I can do it, but not knowing the exact number of elements that will be created, I don't know how to add the correct number of button listener.
AJAX:
success : function(data, status, xhr) {
$("#risultatoLibriCercati").empty();
var divContent = "";
for (var i = 0; i < data.length; i++) {
divContent +=
"<div class='col-sm-2 mt-4'><a data-toggle='modal' data-target='#bookPage" +
[i] +
"'><div class='card shadow-sm'><img style='height:250px' src='" +
data[i].imgLink +
"' class='img-thumbnail rounded'></div></a></div><div class='modal fade' id='bookPage" +
[i] +
"'><div class='modal-dialog'><div class='modal-content'><div class='modal-header text-center'><h4 class='modal-title w-100 dark-grey-text font-weight-bold'>" +
data[i].titolo +
"</h4><button type='button' class='close' data-dismiss='modal' aria-lable='close'>×</button></div><div class='mt-4' style='background: url(" +
data[i].imgLink +
") no-repeat;background-size: contain; background-position: center; min-height: 300px;'></div><div class='modal-body mx-4'><div class='md-form'><p class='font-small'>" +
data[i].autore +
"</p></div><div class='md-form'><p>" +
data[i].descrizione +
"</p></div><div class='text-center mb-3'><button class='btn btn-primary btn-block z-depth-1a' id='aggiungi" +
[i] +
"'>Aggiungi a libreria</button><a href='" +
data[i].isbn13.replace("'", " ") +
"' target='_blank' style='border:none;text-decoration:none'><img src='https://www.niftybuttons.com/amazon/amazon-button2.png'></a></div></div></div></div></div><input type='hidden' id='categoria" +
[i] +
"' value='" +
data[i].categoria +
"'><input type='hidden' id='googleID" +
[i] +
"' value='" +
data[i].googleID +
"'><input type='hidden' id='titolo" +
[i] +
"' value='" +
data[i].titolo.replace("'", " ") +
"'><input type='hidden' id='descrizione" +
[i] +
"' value='" +
data[i].descrizione.replace("'", " ") +
"'><input type='hidden' id='autore" +
[i] +
"' value='" +
data[i].autore +
"'><input type='hidden' id='isbn" +
[i] +
"' value='" +
data[i].isbn13.replace("'", " ") +
"'><input type='hidden' id='voto" +
[i] +
"' value='" +
data[i].voto +
"'><input type='hidden' id='imgLink" +
[i] +
"' value='" +
data[i].imgLink +
"'>";
}
$("#risultatoLibriCercati").append(divContent);
}
BUTTON ON CLICK LISTENER:
$(document).on('click', '#aggiungi0', function(){
var book = {
googleID: $("#googleID0").val(),
titolo: $("#titolo0").val(),
descrizione: $("#descrizione0").val(),
isbn13: $("#isbn0").val(),
voto: $("#voto0").val(),
imgLink: $("#imgLink0").val(),
autore: $("#autore0").val(),
categoria: $("#categoria0").val(),
userId: getCookie("userId"),
};
$.ajax({
[...]
You can add class attribute for those buttons and attach event and index for them as below
var btnIndex = 0;
$('#add').on('click', function() {
$('.container').append(`<button class="new-btn" data-index=${btnIndex++}>Button test</button>`);
});
$('.container').on('click', '.new-btn', function(e) {
console.log("clicked" + $(e.target).data("index"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="container"></div>
And passing these values by index into ajax call like this:
$(document).on('click', '.new-btn', function(e){
const idx = $(e.target).data("index");
var book = {
googleID: $("#googleID" + idx).val(),
titolo: $("#titolo" + idx).val(),
descrizione: $("#descrizione" + idx).val(),
isbn13: $("#isbn" + idx).val(),
voto: $("#voto" + idx).val(),
imgLink: $("#imgLink0" + idx).val(),
autore: $("#autore" + idx).val(),
categoria: $("#categoria" + idx).val(),
userId: getCookie("userId"),
};
$.ajax({
[...]

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

How to create a DataTable responsive filled from $.Ajax

I am developing an app which displays many information from a web-service query, the data-table fills the information correctly and it displays the style correctly too, but when I try to see the information in a mobile device the Data-table is looking very bad.
I am using $.Ajax method to fill the information.
JavaScript:
$.ajax({
type: 'POST',
url: '/enrollment.asmx/Searcher',
data: JSON.stringify(JsonObj),
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
$("#loadingDiv").hide();//Show Loader
var html = " <table id=\"db\" class=\"table-hover dt-responsive nowrap table table-bordered\"><thead><tr><th data-priority='1'>Selection</th><th>City</th><th>Zip</th><th>Address</th><th>State</th><th>ESIID</th><th>Utility</th></tr></thead><tbody>";
for (var i = 0; i < data.d.length; i++) {
html = html + "<tr name='userinformation' onclick=\"rowSelected('" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "');\" id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "'><td><input type='radio' name='userinformation' value='#'></td></td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollCity'>" + data.d[i].SEnrollCity + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollZip'>" + data.d[i].SEnrollZip + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollStreet'>" + data.d[i].SEnrollStreet + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SState'>" + data.d[i].SState + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEsiid'>" + data.d[i].SEsiid + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SUtility'>" + data.d[i].SUtility + "</td></tr>";
_vDistributionServiceProviderID = data.d[i].SDistributionServiceProviderID;
_vStateCode = data.d[i].SStateCode;
}
console.log("Dis: " + _vDistributionServiceProviderID);
html = html + "</tbody></table>";
$("#dbResultTable").html(html);//We have the Append here
$("#lblCheck").show();
if ($('#db thead').length > 0) {
var table = $("#db").DataTable();
$(table).remove();
var table = $("#db").DataTable();
table.draw();
}
else {
var table = $("#db").DataTable();
table.draw();
}
$("#submit").show();
$("#lblSelection").show();
$("#lblSelectionInfo").show();
if (data.d.SError == "" || data.d.SError == null) {
//Write an error
}
else {
alert("Error 1");
$("#divResult").html(data.d.SError);
alert(JSON.stringify(data.d.SError));
}
},
error: function (e) {
//alert("Error 2");
alert("The error is: " + JSON.stringify(e));
$("#divResult").html(data.d.SError);
alert(JSON.stringify(data.d.SError));
}
});
Initialize the Data-table.
var table = $("#db").DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: -1 }
]
});
Unfortunately in the responsive device it look awful. Could somebody please help me this issue?
Thanks in advance.
Your initial stage of data table
var table = $("#db").DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: -1 }
]
});
Get the data using ajax:
$.ajax({
type: 'POST',
url: '/enrollment.asmx/Searcher',
data: JSON.stringify(JsonObj),
success:function(data){
var json=JSON.parse(data);
table.fnClearTable();
table.fnAddData(json);
}
});

Javascript: TypeError: $.chat is not a function

I have the following javascript code snippet, which defines the chat funtion, it should create a chat in a Sharepoint site.
However I get "TypeError: $.chat is not a function", does anyone know how I could fix this?
Edit: I get this error when I try calling this function:
$(document).ready(function() {
$.chat({
listguid: "{3A076D9D-362B-455A-8F19-831F6716B6F0}"
});
});
(function($) {
$.chat = function(options) {
$.chat.settings = $.extend({
listguid: '0',
divid: 'jQueryChatBox',
savecaption: 'Send',
clearcaption: 'Clear',
messagecolumn: 'Message'
},
options || {});
ChatBox = "<input type='text' size='50' id='" + $.chat.settings.divid + "textbox' name='" + $.chat.settings.divid + "textbox'/><br/><input type='submit' id='" + $.chat.settings.divid + "submitbutton' value='" + $.chat.settings.savecaption + "'/><input type='reset' value='" + $.chat.settings.clearcaption + "'/>";
$('#' + $.chat.settings.divid).html(ChatBox);
$('#' + $.chat.settings.divid + 'submitbutton').click(
function() {
if ($.trim($('#' + $.chat.settings.divid + 'textbox').val()) == "")
return false;
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> <listName>" + $.chat.settings.listguid + "</listName> <updates> <Batch OnError=\"Continue\"> <Method ID=\"1\" Cmd=\"New\"> <Field Name=\"" + $.chat.settings.messagecolumn + "\">" + $('#' + $.chat.settings.divid + 'textbox').val() + "</Field> </Method> </Batch> </updates> </UpdateListItems> </soap:Body> </soap:Envelope>";
$.ajax({
url: L_Menu_BaseUrl + "/_vti_bin/lists.asmx",
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems")
},
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=utf-8"
});
$('#' + $.chat.settings.divid + 'textbox').val('');
return false;
})
}
})
(jQuery);
$(document).ready(function() {
$.livelistdata({
prompt: false,
interval: 100,
opacity: '0.5'
})
});

Categories

Resources