I am getting Json data in output and appended to table with edit option, so what I want is when click on Edit of td then clicked td element text should change from 'Edit' to 'Save' and when click on 'save' again it change to edit, but at time one td element should change from 'Edit' to 'Save' at atime only one 'Save' should active and others remain 'Edit' .
<table class="append_data">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
<th>Action</th>
</tr>
</table>
//script to get data:
$.ajax({
url: "<?= base_url('controller/get_users') ?>",
type: 'POST',
data: {
},
success: function (myJSON) {
var output = myJSON;
var html = '';
$.each(output, function (key, value) {
html += '<tr>';
html += '<td>' + value.name + '</td>';
html += '<td>' + value.mobile + '</td>';
html += '<td>' + value.id + '</td>';
html += '<td><span class="change_res' + value.id + '">Edit</span></td>';
html += '</tr>';
});
$('.append_data tbody').append(html);
},
error: function (xhr) {
alert(xhr.status);
}
});
//script to change text
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$(this).text('Save').siblings().text('Edit');
});
getting output:
Expected output:
you can try
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$('.edit_user').not(this).text('Edit'); // back all the edit_user to Edit but not this
$(this).text(($(this).text().trim() == 'Save') ? 'Edit' : 'Save'); // change the text for this between Edit or Save
});
Explanation :
$('.edit_user').not(this).text('Edit'); back all other elements text to Edit
$(this).text().trim() == 'Save') ? 'Edit' : 'Save' is a short hand method of if statement .. means if the text of the element is Save set it to Edit and vice versa .. and about .trim() here for double check that the text is exactly equal the string
Related
My code could display the data without the onclick function but when it's added the data does not display in my table. There are no errors being displayed as well.
This is the code to get the json data and display:
<script>
var url = "http://127.0.0.1:8080/Assignment2/video/backend/RestController.php?view=all";
$('#viewUser').on('click',function (e){
$.ajax({
method: "GET",
cache: false,
url: url,
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
student += '<tr>';
student += '<td>' +
value.id + '</td>';
student += '<td>' +
value.username + '</td>';
student += '<td>' +
value.videoName + '</td>';
student += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#table').append(student);
},
error:function(exception){alert('Exeption:'+exception);}
})
e.preventDefault();
});
</script>
This is the code for the button (for onclick function):
<h2>View Stored User</h2>
<button type="button" id="viewUser">GO</button>
[The error i'm receiving from the console log of the browser tho it's not related][1]
[1]: https://i.stack.imgur.com/7TZ3a.png
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!
I have this JavaScript
function pickdet(Id) {
//alert(Id);
var dd = Id;
$.ajax({
cache: false,
url: "/PVSigns1/GetDetails",
data: { 'Id' : Id },
type: "GET",
dataType: "json",
success: function (data) {
//alert('i dey here')
var row = "";
var baseurl = '#Url.Action("Edit","PVSigns1")' + '?Id=';
$.each(data, function (index, item) {
var clickUrl = baseurl + item.PVSignId;
//row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue + "</td><td> <input type= 'button' onclick= location.href = + '<Url.Action("Create", "PVSigns1", new { Id = item.PVSignId }) ' />" + "</td></tr>";
row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue +
"</td><td> <button class='editbtn btn btn-xs btn-success' data-url = '" + clickUrl + "'> <i class='fa fa-edit fa-lg'></i> Edit</button></td></tr>";
});
$("#pvv").html(row);
},
error: function (result) {
$("#pvv").html('Nothing to show <br /> <p />' + result);
}
});
}
$(function () {
$("button.editbtn").click(function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
});
When I run it, it display perfectly on the browser, but the link created don't work, and when I view the page source, the tbody part which the code above is supposed to inject, doesn't get rendered.
This is what I get, Click on any of the green buttons
in the top table, it loads the second table. The issue is with the second table.
Note: I am using JQuery Datatables.
This the rendered output from page source
<div>
<h3> Details</h3>
<table id="Pv" class="table table-condensed">
<thead>
<tr>
<th>Sign</th>
<th> Value </th>
<th></th>
</tr>
</thead>
<tbody id="pvv">
</tbody>
</table>
Notice <tbody id="pvv"> is empty, not table elements there. What is the issue?
You need to use delegation of dom element for click event. which element generated after binding event after existing dom
$("#Pv").on('click','button.editbtn', function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
I am dynamically creating a table using data from an AJAX call. I am using a "select/dropdown box" .on('change') function to send values to my PHP. Once the table displays, I want to set focus to a search box dynamically created on the table.
The trouble seems to be that since the table takes a couple seconds to become visible, the .focus() command fires before the table is visible. I would like to have the .focus() command fire after the create table function completes.
Javascript/Jquery Code:
$('#t6F3Box1').on('change', function()
{
var $newTable ='<table id="tempEmployerTbl" class="studentTables"><thead><tr>';
var $searchStr=new RegExp("ID");
var $tableContainerDiv="#t6F3TableCont";
var $rowFlag=0;
var $responseDataValue=[]
var $employerState=$('#t6F3Box1').val();
var $getTableDataPhp="../application/employer.php";
var $data=[];
$('#t6F3ErrDiv').text('');
$('#t6F3TableCont, #t6F3HLine2, #t6F3HLine2').show();
$data += "&employerState=" + encodeURIComponent($employerState);
$.ajax({
type: 'POST',
async: false,
url: $getTableDataPhp,
cache: false,
datatype: 'json',
data: $data,
success: function($responseData)
{
//Loop through the responsdata returned in a JSON Array
//dynamically create the Employer drop down box
if (!$responseData.authenticationError)
{
//Create the header for the Employer Table
$.each($responseData, function($key, $value)
{
if($rowFlag==0)
{
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<th class="tableDataHide">' + $keys + '</th>';
}
else
{
$newTable += '<th class="tableDataShow">' + $keys + '</th>'
}
});
$rowFlag=1;
}
});
$newTable +='</tr></thead><tbody>';
//Create the body for the Employer Table
$.each($responseData, function($key, $value)
{
$newTable += '<tr>'
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<td class="tableDataHide">' + $values + '</td>';
}
else
{
if($values==null)
{
$values="";
}
$newTable += '<td class="tableDataShow">' + $values + '</td>'
}
});
$newTable +='</tr>';
});
$newTable +='</tbody></table>';
$($tableContainerDiv).html($newTable);
$("#tempEmployerTbl").dataTable();
$('#tblSearchBox').focus();
}
}
});
I don't see where you even call .focus in your example, but the solution is simply to call it after the $($tableContainerDiv).html($newTable); -- i.e. after it's appended by the ajax callback.
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
});