How to move (append) all rows into another table with js - javascript

I want to select all my data rows and automatically goes into another table,
but i didnt find a way to do it.
my current condition using Jquery to move it 1 by 1 using code below
$("#tblcandidate").on("change", ".chkCheckBoxId", function () {
if ($(".chkCheckBoxId").is(":checked")) {
$(".fail").hide();
var trItem = $(this).closest("tr");
trItem.find(".chkCheckBoxIdFail").closest("td").remove();
trItem.add("<tr>").append("</tr>");
$("#tblcandidateprocess").append(trItem);
}
});
and my target is making function that can append all my row into another table using button
EDIT:
My datatables come from ajax belox
function loadData(monthyear) {
return $.ajax({
url: "#Url.Action("ListCandidate", "Recruitment")?monthyear=" + monthyear,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
beforeSend: function () {
swal.fire({
title: "Please wait a moment",
text: "Loading data...",
showConfirmButton: false,
allowOutsideClick: false,
willOpen: () => {
Swal.showLoading()
},
});
},
success: function (data) {
var getTemp = "#TempData["Allert"]";
if (getTemp === "Data successfully selected") {
Swal.fire({
text: getTemp,
icon: "success",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else if (getTemp === "Something Went Wrong") {
Swal.fire({
text: getTemp,
icon: "error",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else {
swal.close();
}
var html = '';
// delete existing row if any
table.clear().draw();
$.each(data, function (key, item) {
var TglLahir = item.TglLahir;
var cvTglLahir = moment(TglLahir).format('YYYY-MM-DD') ;
if (item.NamaS2 != null || item.NamaS2 != "") {
var namas2 = item.NamaS2;
}
else {
var namas2 = "A";
}
if (item.NamaS1 != null || item.NamaS1 != "") {
var namas1 = item.NamaS1;
}
else {
var namas1 = "A";
}
if (item.NamaD3 != null || item.NamaD3 != "") {
var namad3 = item.NamaD3;
}
else {
var namad3 = "A";
}
html += '<tr class="text-capitalize">';
html += '<td><span class="d-none">' + "'" + '</span> <div class="d-flex flex-column justify-content-start fw-bold">' + item.NomorKTP+'</div></td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.NamaLengkap.toLowerCase() + '</td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.PosisiYangDilamar.toLowerCase() + '</td>';
and etc
Then I want to move the shown row from this table A to my Table B

Here is an updated version of my Vanilla-JavaScript implementation that transfers individual <tr>s between the <tbody>s of the two tables:
document.querySelectorAll("button").forEach(b=>b.onclick=ev=>{
let tr=b.closest("tr");
document.querySelector((tr.closest("table").id=="source"?"#target":"#source")+" tbody").append(tr);
});
<div id="content">
<table id="source">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody>
<tr><td>1 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>2 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>3 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>4 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
</tbody>
</table>
<hr>
<table id="target">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody></tbody></table>
</div>

Related

Pagination for Dropdownlist filter data in ASP.NET MVC

My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.

Dynamically created table does not display correctly on reload

I am dynamically creating a table using JavaScript/jQuery/html from an Ajax call. The first time the table loads it displays correctly formatted. However, when I do a refresh/reload the formatting of the table is not correct. I have included Promise to try and fix it as per How to Promisify an Ajax Call
Correct on first load:
After reload:
The abbreviated code is:
$('#refreshTableBtn').click(function(){
//Re-display the exercise table
exerciseFirstColumnDetails()
.then((numExeDetails) => {
console.log(numExeDetails)
loadExerciseDetails(numExeDetails)
})
.catch((error) => {
console.log()
})
});
function exerciseFirstColumnDetails() {
//Get Patient Exercise Details
$('#exerciseTable tr').empty();
var numExeDetails = 0;
//Get the Patient's exercise headers
return new Promise((resolve, reject) => {
$.ajax({
url: "PatientExerciseHeadersListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
reject();
})
.done(function(responseJson1a) {
dataType: "json";
if (Object.keys(responseJson1a)[0] == "empty") {
$('#ajaxGetUserServletResponse4').text('No Exercise details.');
}else {
//Create first table column
//Loop through the Execise details
//Populate the variable number of exercise variables and keep count.
$.each(responseJson1a, function() {
numExeDetails++;
var html = "";
html += "<tr id='ExerciseDetail"+numExeDetails+"' name='" + this.edeId + "'>";
html += "<td class='bgColourWhiteBold sticky-col'>"+ this.edeType + " - " + this.edeUnit + "</td>"
html += "</tr>"
$(html).insertBefore($("#InsertSet"));
});
}
resolve(numExeDetails);
});
});
};
function loadExerciseDetails(numExeDetails) {
$.ajax({
url: "PatientExerciseDetailsListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
viewFrom : $("#viewFromDate").val(),
viewTo : $("#viewToDate").val(),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
})
.done(function(responseJson1a) {
dataType: "json";
$('#ajaxGetUserServletResponse4').text('');
if (Object.keys(responseJson1a)[0] == "empty") {
//Display an empty table for data entry
//Check if the date range includes today's date.
if (moment($("#viewFromDate").val(), 'DD/MM/YYYY').isAfter(moment())
|| moment($("#viewToDate").val(), 'DD/MM/YYYY').isBefore(moment())){
$('#ajaxGetUserServletResponse4').text('No Patient exercises in this date range.');
}else {
var today = moment(new Date()).format("DD/MM/YYYY");
var todayDay = moment(new Date()).format('ddd')
//If the date range includes todays date then display an empty table for data entry
$("<th class='h1Colour'>Set 1</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 2</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 3</th>").appendTo($("#tableHeadersSet"));
//Create three sets for each Exercise Detail
for(let i = 1; i <= numExeDetails; i++) {
var ExerciseDetail = "ExerciseDetail" + i;
alert(ExerciseDetail);
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='1' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='2' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='3' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
}
}
}else{
//Display existing sets
}
});
}
HTML:
<table id='exerciseTable'>
<tr id="tableHeadersSet">
<!-- Place for Set row -->
</tr>
<tbody id="tableBody">
<!-- Add each of the Exercise Details -->
<tr id="InsertSet">
<!-- Place for Insert Set button -->
</tr>
</tbody>
</table>
The answer is to move the population of the first column to where I do the input lines.
$('#refreshTableBtn').click(function(){
//Re-display the exercise table
exerciseFirstColumnDetails()
.then(({numExeDetails, exercises}) => {
console.log({numExeDetails, exercises})
loadExerciseDetails({numExeDetails, exercises})
})
.catch((error) => {
console.log(error + " Error in exerciseOverview.js - call 'loadExerciseDetails' function");
})
});
function exerciseFirstColumnDetails() {
//Get Patient Exercise Details
$('#exerciseTable tr').empty();
var numExeDetails = 0;
var exercises = [];
//Get the Patient's exercise headers
return new Promise((resolve, reject) => {
$.ajax({
url: "PatientExerciseHeadersListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
reject();
})
.done(function(responseJson1a) {
dataType: "json";
if (Object.keys(responseJson1a)[0] == "empty") {
$('#ajaxGetUserServletResponse4').text('No Exercise details.');
}else {
// $("#chartDisp").show();
//Create first table column
$("<th class='h2Colour sticky-col' colspan='1'>Week</th>").appendTo($("#tableHeadersWeek"));
$("<th class='bgColourWhite sticky-col' colspan='1'>Date</th>").appendTo($("#tableHeadersDate"));
$("<th class='bgColourWhite sticky-col' colspan='1'>Day</th>").appendTo($("#tableHeadersDay"));
$("<th colspan='1' class='tdNoBorder sticky-col'></th>").appendTo($("#tableHeadersSpace1"));
$("<th class='tdNoBorder sticky-col'></th>").appendTo($("#tableHeadersSet"));
//Loop through the Execise details
//Populate the variable number of exercise variables and keep count.
$.each(responseJson1a, function() {
//Pass 'exercises' to the next funtion
exercises[numExeDetails] = this.edeType + " - " + this.edeUnit;
numExeDetails++;
var html = "";
html += "<tr id='ExerciseDetail"+numExeDetails+"' name='" + this.edeId + "'>";
// html += "<td class='bgColourWhiteBold sticky-col'>"+ this.edeType + " - " + this.edeUnit + "</td>"
html += "</tr>"
$(html).insertBefore($("#InsertSet"));
});
$("<td class='tdNoBorder sticky-col' colspan='1'></td>").appendTo($("#InsertSet"));
}
resolve({numExeDetails, exercises});
});
});
};
function loadExerciseDetails({numExeDetails, exercises}) {
$.ajax({
url: "PatientExerciseDetailsListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
viewFrom : $("#viewFromDate").val(),
viewTo : $("#viewToDate").val(),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
})
.done(function(responseJson1a) {
dataType: "json";
$('#ajaxGetUserServletResponse4').text('');
if (Object.keys(responseJson1a)[0] == "empty") {
//Check if the date range includes today's date.
if (moment($("#viewFromDate").val(), 'DD/MM/YYYY').isAfter(moment())
|| moment($("#viewToDate").val(), 'DD/MM/YYYY').isBefore(moment())){
$('#ajaxGetUserServletResponse4').text('No Patient exercises in this date range.');
}else {
var today = moment(new Date()).format("DD/MM/YYYY");
var todayDay = moment(new Date()).format('ddd')
//If the date range includes todays date then display an empty table for data entry
$("<th class='h2Colour' colspan='3'>1</th>").appendTo($("#tableHeadersWeek"));
$("<th class='h1Colour' colspan='3'>" + today + "</th>").appendTo($("#tableHeadersDate"));
$("<th class='h1Colour' colspan='3'>" + todayDay +"</th>").appendTo($("#tableHeadersDay"));
$("<th colspan='3' class='tdNoBorder'></th>").appendTo($("#tableHeadersSpace1"));
$("<th class='h1Colour'>Set 1</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 2</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 3</th>").appendTo($("#tableHeadersSet"));
//Create three sets for each Exercise Detail
var exercisesIdx = 0;
for(let i = 1; i <= numExeDetails; i++) {
var exerciseDetail = "ExerciseDetail" + i;
$("<td class='bgColourWhiteBold sticky-col'>"+ exercises[exercisesIdx] +"</td>").appendTo($('#'+exerciseDetail));
exercisesIdx++;
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='1' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='2' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='3' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
}
$("<td class='tdNoBorder sticky-col' colspan='3'><input type='button' name='addSetBtn' class='btn btn-sm h2Colour' style='width:100%' value='Add Set'></td>").appendTo($("#InsertSet"));
}
}else{
//Display existing sets
}
});
}

jquery.min.js:2 jQuery.Deferred exception: Cannot read property 'on' of undefined TypeError: Cannot read property 'on' of undefined

I am trying to make a CRUD table using laravel and AJAX. Trying out the tutorial from Webslesson. Here is the tutorial link : https://www.webslesson.info/2018/12/live-table-add-edit-delete-in-laravel-using-ajax-jquery.html
I've tried may ways and it doesnt seem to work.
Here is my Javascript code.
$(document).ready(function(){
fetch_data();
function fetch_data()
{
$.ajax({
// url:"/enquiry/fetch_data",
url:"{{url('/enquiry/fetch_data')}}",
dataType:"json",
success:function(data)
{
var html = '';
html += '<tr>';
html += '<td contenteditable id="ac_assign"></td>';
html += '<td contenteditable id="item_cat"></td>';
html += '<td contenteditable id="itemDesc"></td>';
html += '<td contenteditable id="deliveryDate"></td>';
html += '<td contenteditable id="qty"></td>';
html += '<td contenteditable id="unit"></td>';
html += '<td contenteditable id="assetNo"></td>';
html += '<td contenteditable id="remark"></td>';
html += '<td><button type="button" class="btn btn-success btn-xs" id="add">Add</button></td></tr>';
for(var count=0; count < data.length; count++)
{
html +='<tr>';
html +='<td contenteditable class="column_name" data-column_name="ac_assign" data-id="'+data[count].id+'">'+data[count].ac_assign+'</td>';
html += '<td contenteditable class="column_name" data-column_name="item_cat" data-id="'+data[count].id+'">'+data[count].item_cat+'</td>';
html += '<td contenteditable class="column_name" data-column_name="itemDesc" data-id="'+data[count].id+'">'+data[count].itemDesc+'</td>';
html += '<td contenteditable class="column_name" data-column_name="deliveryDate" data-id="'+data[count].id+'">'+data[count].deliveryDate+'</td>';
html += '<td contenteditable class="column_name" data-column_name="qty" data-id="'+data[count].id+'">'+data[count].qty+'</td>';
html += '<td contenteditable class="column_name" data-column_name="unit" data-id="'+data[count].id+'">'+data[count].unit+'</td>';
html += '<td contenteditable class="column_name" data-column_name="assetNo" data-id="'+data[count].id+'">'+data[count].assetNo+'</td>';
html += '<td contenteditable class="column_name" data-column_name="remark" data-id="'+data[count].id+'">'+data[count].remark+'</td>';
html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button></td></tr>';
}
$('tbody').html(html);
}
});
}
var _token = $('input[name="_token"]').val();
$(document).on('click', '#add', function(){
var ac_assign = $('#ac_assign').text();
var item_cat = $('#item_cat').text();
var item_cat = $('#itemDesc').text();
var item_cat = $('#deliveryDate').text();
var item_cat = $('#qty').text();
var item_cat = $('#unit').text();
var item_cat = $('#assetNo').text();
var item_cat = $('#remark').text();
if(ac_assign != '' || item_cat != '' || itemDesc != '' || deliveryDate != '' || qty != '' || unit != '' || assetNo != '' || remark != '' )
{
$.ajax({
url:"{{ route('enquiry.add_data') }}",
method:"POST",
data:{ac_assign:ac_assign, item_cat:item_cat, itemDesc:itemDesc, deliveryDate:deliveryDate, qty:qty, unit:unit, assetNo:assetNo, remark:remark, _token:_token},
success:function(data)
{
$('#message').html(data);
fetch_data();
}
});
}
else
{
$('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
}
});
$(document).on('blur', '.column_name', function(){
var column_name = $(this).data("column_name");
var column_value = $(this).text();
var id = $(this).data("id");
if(column_value != '')
{
$.ajax({
url:"{{ route('enquiry.update_data') }}",
method:"POST",
data:{column_name:column_name, column_value:column_value, id:id, _token:_token},
success:function(data)
{
$('#message').html(data);
}
})
}
else
{
$('#message').html("<div class='alert alert-danger'>Enter some value</div>");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Are you sure you want to delete this records?"))
{
$.ajax({
url:"{{ route('enquiry.delete_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#message').html(data);
fetch_data();
}
});
}
});
});
Here is my blade
<div class="panel-body">
<div id="message"></div>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<!-- <th>NO</th> -->
<th>A/C ASSIGN</th>
<th>ITEM CATEGORY</th>
<th>DELIVERY DATE</th>
<th>ITEM DESC</th>
<th>QTY</th>
<th>UNIT</th>
<th>ASSET NO</th>
<th>REMARK</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{{ csrf_field() }}
</div>
</div>
Here are the functions in my controller
function fetch_data(Request $request)
{
$data = Enquiry::where('formId', $request->formId)->orderBy('id','desc')->get();
// echo $data;
echo json_encode($data);
}
function add_data(Request $request)
{
if($request->ajax())
{
$data = array(
'no' => $request->no,
'deliveryDate' => $request->deliveryDate,
'ac_assign' => $request->ac_assign,
'item_cat' => $request->item_cat,
'itemDesc' => $request->itemDesc,
'qty' => $request->qty,
'unit' => $request->unit,
'assetNo' => $request->assetNo,
'remark' => $request->remark
);
$id = Enquiry::insert($data);
if($id > 0)
{
echo '<div class="alert alert-success">Data Inserted</div>';
}
}
}
function update_data(Request $request)
{
// if($request->ajax())
// {
$data = array(
$request->column_name => $request->column_value,
);
Enquiry::where('formId', $request->formId)
->update($data);
echo '<div class="alert alert-success">Data Updated</div>';
// }
}
function delete_data(Request $request)
{
// if($request->ajax())
// {
Enquiry::where('id', $request->id)
->delete();
echo '<div class="alert alert-success">Data Deleted</div>';
// }
}
And here is my web.php
Route::get('/enquiry/fetch_data', 'FormController#fetch_data');
Route::post('/enquiry/add_data', 'FormController#add_data')->name('enquiry.add_data');
Route::post('/enquiry/update_data', 'FormController#update_data')->name('enquiry.update_data');
Route::post('/enquiry/delete_data', 'FormController#delete_data')->name('enquiry.delete_data');
This is the error from the console. I have attached an image here.
Thank you.
For some reason i don't know why that happens but here is how to fix it Instead of
npm run dev
just run build
npm run build
Enjoy coding

update status function should not refresh which onchange the dropdownlist using mvc?

When onclick the status update then only corresponding row should be refresh . before that i written the drop down onchange function based on that only table row is display.
cs.html:
<section class="card ">
<div class="card-block">
<h5 class="with-border m-t-lg">View Module List</h5>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInput">Domain Name</label>
#Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { #class = "select2-arrow" })
</fieldset>
</div>
</div>
<br />
<div class="table-responsive" id="findValue" style="display:none;">
<table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
<thead>
<tr>
<th>S#</th>
<th>Module Name</th>
<th>Url</th>
<th>Roles</th>
<th>Action</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
Dropdown based on view tables code:
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Update status Code
<script>
$(document).ready(function () {
$("#example tbody").on('click', '.user-status', function () {
var getId = $(this).data('id');
var status = $(this).attr('data-status');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateStatusModule")',
dataType: 'json',
data: { ModuleID: getId },
success: function (data) {
if (data.success) {
alert(data.message);
$("#example tbody").load("/Account/UpdateStatusModule");
}
},
error: function (ex) {
alert('Failed to retrieve Sub Categories : ' + ex);
}
});
});
});
</script>
i written the drop down onchange function based on that only table row is display. When onclick the status update then only corresponding row should be refresh onchange no value should not be change
#region Update Status
[Authorize]
[HttpPost]
public ActionResult UpdateStatusModule(int ModuleID)
{
try
{
int refID = Convert.ToInt32(Session["RefID"]);
int typeID = Convert.ToInt32(Session["ComTypeID"]);
if (ModelState.IsValid && refID > 0)
{
userType type = new userType();
type.UpdateStatusModule(ModuleID);
}
return Json(new { success = true, message = "updated successfully" }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
#endregion
If you append html after the initialization it can't work.
You need to register events on document(without $(document).ready)
$(document).on("change","#DomainID", function () {
alert("domain changed");
}).on('click', '.user-status', function () {
alert("clicked");
});
For async POST:
$.post("MyUrl",{myId: myId},function(data){
do wathever
}).fail(function(x,y,z){
alert("ops");
});
More simple

checkboxes and number fields set by jquery appear for a split second, then suddenly disappear

I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle

Categories

Resources