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!
Related
I’ve ajax code to append “unit menu” based on “product item” selection.
When I create a new row, and select an item from “product menu” I expected that the “unit input” of the same row must affect and append the “unit menu” belongs to the selection of the "product item" in the same row.
But I noticed that when a new row created by cloning and I select a product (all the above rows also affect, i.e after product item selection the "unit menu" of the same row and the "unit menu" of the above rows also affected)
The next code illustrate what I mean....
$(document).ready(function() {
var purchase = $('.purchase-row').last().clone();
let purchaseCount = 0;
$(document).on('click', '.add_item', function() {
var clone = purchase.clone().prop('id', 'product_' + purchaseCount);
// var clone = purchase.clone().prop('class', 'product_' + purchaseCount);
console.log('clone: ', clone);
$(this).prevAll('.purchase-row').first().after(clone.hide());
clone.slideDown('fast');
$('#product_'+ purchaseCount).find('#id_pro-product').removeClass('product').addClass('newProduct');
$('#product_'+ purchaseCount).find('#id_pro-unit').removeClass('unit').addClass('newUnit');
purchaseCount++;
console.log('PURCHASE-COUNT: ', purchaseCount);// $(this).parent().slideUp('fast');
// The next code for reinitialize select2
var $example = $(".js-programmatic-init").select2();
$example.select2();
});
$(document).on('click', '.purchase-minus', function() {
if (purchaseCount == 0) {
// Do nothing.
alert('You can not delete this row' );
} else {
$(this).closest('.purchase-row').remove();
purchaseCount--;
console.log('PURCHASE-COUNT2: ', purchaseCount);
}
});
$(document).on('click', '.purchase-broom', function() {
$(this).closest('.purchase-row').find('input').val('');
});
$(document).on('change', '.product', function(e){
var id = $(this).val();
console.log('CHANGED-PRODUCT: ', id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
// dataType: 'json',
// async: true,
// cache: false,
data: {
'pro-product': $('.purchase-row select').closest('.product').val(), // this is right
// find('#id_pro-product')
},
success: function (data) {
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
// $('#id_pro-unit').text('');
// $('select').closest('.unit').find('select').text('');
$('select').closest('.unit').text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
// $('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
$('select').closest('.unit').append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
The next image indicates the main row which I want to clone
Image of the main row
The next image indicates an example for creating 2 rows from the main one.
Image of cloning rows
You can notice a bug in the cloning inputs due to using of (select2 plugin),I raised an issue in Select2 forum(but I havegot no answer till now), So I'll ask a new question here about that behavior..
My view to handle ajax
from django.http import JsonResponse
def get_product_unit(request):
data = {}
product = request.POST.get('pro-product')
if product is not None:
unit = UOM.objects.values('unit__name', 'uom_options', 'unit').filter(product_id=product)
print('purchase not purchase')
else:
unit = []
data['unit'] = [(obj['unit__name']) for obj in unit]
print(
'PRODUCT: ', product,
'UNIT: ', unit,
)
return JsonResponse(data)
My tries to fix this problem
1- In fact I tried to make a new ajax call for the new cloned row, but I realize that it can solve by the above ajax code (I don't know how).
I think if I knew to access the "class and id" of the new row itself
$(document).on('change', '.newProduct', function(e){
var id = $(this).val();
console.log('SUCCESS-CHANGE-PRODUCT-FROM-NEW-CLASS: ', id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_new_row_unit" %}',
// dataType: 'json',
// async: true,
// cache: false,
data: {
'pro-product': id,
// $('#product_'+purchaseCount).closest('.newProduct select').val(),
// find('#id_pro-product')
},
success: function (data) {
console.log(
'FROM SUCCESS-NEW-CLASS: ', data['unit'],
'PRODUCT-FROM-NEW-CLASS: ', data['product'],
);
var values_3 = data['unit'];
// $('#id_pro-unit').text('');
// $('select').closest('.newUnit').text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
// $('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
// $('.newUnit select').closest('#product_'+ purchaseCount).append('<option>' + values_3[i] + '</option>');
// $('select').closest('#product_'+ purchaseCount).find('.newUnit').append('<option>' + values_3[i] + '</option>');
//$('select').closest('.newUnit').append('<option>' + values_3[i] + '</option>');
$('.purchase-row #id_pro-unit').append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase-New Class !!!');
},
});
e.preventDefault();
});
});
My view
def get_new_row_unit(request):
data = {}
product = request.POST.get('pro-product')
data['product'] = product
if product is not None:
unit = UOM.objects.values('unit__name', 'uom_options', 'unit').filter(product_id=product)
else:
unit = []
data['unit'] = [(obj['unit__name']) for obj in unit]
print(
'PRODUCT: ', product,
'UNIT: ', unit,
)
return JsonResponse(data)
2- Also I tried to do like this Answer But I failed.
3- Also I follow instructions in this answer
But I get the "unit menu" of the main row in all new row when I select an item from the "product menu" in the new row.
My Problem in brief
When I select an item from "product" menu in the first "new cloned row" (or from any new rows)."unit menu" append to all above rows.
What I want to achieve
I want when I select an item from "product menu" only "unit menu" append to the "unit input" of the same row.
I knew that I've missed something but I failed to discover it.
Any suggestions will be appreciated.
=============================================================
My Answer To This Issue After searching and Thinking
=============================================================
Finally I fix my issue as usual (thanks to stackoverflow community).
I want to share my solution of this issue.
Really it took time to understand how it works and how to access the new row or (in other words "how to access the row inputs itself").
My Problem in brief :
When I select an item from "product" menu in the first "new cloned row" (or from any new rows)."unit menu" append to all above rows.
After searching on the web and searching here in the community questions. I found the next answers are useful and helpful.
Thanks to this answer by #martynas
Thanks to this answer by #Евгений Одинец
Thanks to this tutorial
And as I said it can be done by one ajax call.
1- In fact I tried to make a new ajax call for the new cloned row, but I realize that it can solve by the above ajax code (I don't know how).
The final code has became as follow
$(document).on('change', '.product', function(e){
var product_id = $(this).val();
let $el = $(this).closest('.purchase-row');
console.log('SUCCESS-CHANGE-PRODUCT: ', product_id,);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
data: {
'pro-product': product_id,
},
success: function (data) {
if (purchaseCount == 0) {
console.log('purchase count equal to ZERO: ');
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
$el.find('.unit').append('<option>' + values_3[i] + '</option>');
}
}
} else {
let unit = $el.find('.newUnit'); // here I can access the "unit input" of the same row of the "product input"
var values_3 = data['unit'];
unit.text('');
console.log('COUNT IS NOT EQUAL TO ZERO:', values_3);
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
unit.append('<option>' + values_3[i] + '</option>');
}
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
Also I found some answers about how to copy table row to another table and these answers help me a lot.
Here is some of them
How to pass clicked/selected row data from one table to another table
Remove row from one table and add it to another with jQuery
How to read dynamically generated HTML table row's 'td' value
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) {
}
})
i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
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.
I'm quite new to webdevelopment and AJAX and I'm facing a little issue there. Basically, I have a form on my webpage. When I submit this form, it makes an AJAX call to my controller, send me the data I want back, and change the html content of the page.
JS code :
$(document).ready(function() {
$("#mydiv table tbody td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$('#myform').submit(function()
{
try {
var host = $("#host").val();
var port = $("#port").val();
var username = $("#username").val();
var password = $("#password").val();
var database = $("#database").val();
$.ajax({
type: "POST",
url: "/management/connectDatabase",
dataType: "JSON",
data: "host="+host+"&port="+port+"&username="+username+"&password="+password+"&database="+database,
cache: false,
success:
function(data){
$('#mydiv').html(show_tables(data));
},
});
return false;
}
catch(e){
console.debug(e);
}
});
});
function show_tables(data)
{
var html = '<div id="mydiv">';
html += '<table class="display" id="example">';
html += '<thead><tr><th>Tables</th></tr></thead><tbody>';
for (var tablesCount = 0; tablesCount < data.tables.length; tablesCount++){
html += '<tr class=gradeA id="trtest">';
html += '<td id="tdtest">' + data.tables[tablesCount] + '</td>';
html += '</tr>';
}
html += '</tbody></table>';
html += '</div>';
return html;
}
When I submit the form, the HTML is generating right, and I can see my content. But, I can't click on any entries of the <table>. Moreover, when I want to see the sourcecode of my page, it doesn't displays me the table, but still my form, even if it has still been validated.
Could someone explain me what I do wrong here ?
Depending on which jQuery version you're using, you need to either bind the click event using jQuery.delegate or jQuery.on in order for things to work with dynamically added DOM elements.
Edit: as pointed out by Geert Jaminon, you have to use the selector parameter of the on function. This works for me.
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() + "My TR is:" + $(this).parent("tr").html());
});
.live() is replaced by .on() in the newer jQuery versions.
http://jsfiddle.net/ZqYgv/
you need to bind the click event handler after the rendering of the elements, since they weren't in place when you made the binding.
If you insert data dynamically, you need to add the click event after the data has been inserted.
http://codepen.io/thomassnielsen/pen/FEKDg
$.post('ajax/test.html', function(data) {
$('.result').html(data);
// Add .click code here
});