Is it possible to call an html class with specific id, because for now I have same functionality in my class then I need to pull it through class + id to be specific.
I have button that populates data to my table:
<button type="button" onclick="loadData()">Get Data</button>
and I have two tables with the same class name:
<table class="sortable" id="1">
<thead>
<tr>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<table class="sortable" id="2">
<thead>
<tr>
<th>First Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
My aim is to update only the first table which has the id of 1. because right now when I clicked the button both of them will update since they have the same class name. Is it possible if they can Identify by class name + id?
here is my update:
function loadData() {
$.ajax({
url: '/Home/ReadDB',
type: 'GET',
dataType: 'json',
success: function (data) {
var row = '';
$.each(data, function (i, item) {
row += '<tr><td>' + item.LName + '</td><td>' + item.age
+ '</td><td>' + '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Add </button >' + '</td></tr>';
});
console.log(row)
$('.sortable tbody').html(row); // --This one overrides my previous result and want to identify by id
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
First change your ID name please read this answer https://stackoverflow.com/a/70586/2724173
and then concatenate them with like this
$('.sortable#IDname tbody').html(row);
Try this
$.('#1.sortable tbody').html(row);
Simple:
var firstTable = $('.sortable[id="1"]');
console.log(firstTable);
Related
I want to get the date of the same row when I click on Hold Button in the same row. I have tried more searching on Google but I couldn't find any helpful query to fix this issue.
I am new in ajax that's why I need help from this community. Please help me fix it.
Here is what I am trying:
HTML:
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>User ID</th>
<th>Date</th>
<th>Name</th>
<th>User Status</th>
<th colspan="4" class="text-center">Action</th>
</tr>
</thead>
<tbody id="load-table">
<!-- dummy data for StackOverFlow to show you data (By the way this data is dynamic coming from a database. I have placed dummy data only to show the output. So you can ignore data in #load-table)-->
<tr>
<td>1</td>
<td class="statsdate">2022-02-12</td>
<td>Jhon</td>
<td>Active</td>
<td><Button class="hold" data-holdid="holdid">Hold</Button></td>
</tr>
<tr>
<td>4</td>
<td class="statsdate">2022-02-11</td>
<td>Michele</td>
<td>Active</td>
<td><Button class="hold" data-holdid="holdid">Hold</Button></td>
</tr>
<tr>
<td>10</td>
<td class="statsdate">2022-02-10</td>
<td>William</td>
<td>Active</td>
<td><Button class="hold" data-holdid="holdid">Hold</Button></td>
</tr>
</tbody>
</table>
AJAX:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#load-table").append(
"<tr>"
+ "<td>" + value.id + "</td>" +
"<td class='statsdate'>" + statsDate + "</td>" +
"<td>" + value.full_name + "</td>" +
"<td><button type='button' title='Approve this user stat' class='approve btn btn-success btn-rounded btn-icon' data-approveid='" + value.id + "'><i class='typcn typcn-thumbs-up'></td>" +
"<td><button type='button' title='Mark as Hold' class='hold btn btn-danger btn-rounded btn-icon' data-holdid='" + value.id + "'><i class='typcn typcn-archive'></td>" +
"</tr>"
);
});
//Hold user by clicking on hold modal
$(document).on("click",".hold",function(){
var answer = window.confirm("Are You sure to mark this user as Hold?");
if (answer) {
var holdid = $(this).data("holdid");
var sts_date = $(this).closest(".statsDate").text();
var obj = {uID : holdid, date: sts_date};
var myJSON = JSON.stringify(obj);
console.log(myJSON);
}
else {
$("#usersCount").html("");
}
});
</script>
Here is an image to make my question clear.
Image:
Question Image
Please help me fix it. Thanks in advance!
The issue is because closest() only looks through the parent elements of the target. In your HTML, .statsdate is a child of the sibling to the parent. As such the simplest way to do what you need is to use closest() to get the common parent tr, then find() to get the .statsdate.
Also note that the class is statsdate, not .statsDate - case is important in selectors.
var sts_date = $(this).closest('tr').find(".statsdate").text();
Working example:
$(document).ready(function() {
let statsDate = (new Date()).toLocaleDateString();
let value = {
id: '123',
full_name: 'foo bar'
}
$("#load-table").append(
"<tr>" +
"<td>" + value.id + "</td>" +
"<td class='statsdate'>" + statsDate + "</td>" +
"<td>" + value.full_name + "</td>" +
"<td><button type='button' title='Approve this user stat' class='approve btn btn-success btn-rounded btn-icon' data-approveid='" + value.id + "'><i class='typcn typcn-thumbs-up'></td>" +
"<td><button type='button' title='Mark as Hold' class='hold btn btn-danger btn-rounded btn-icon' data-holdid='" + value.id + "'><i class='typcn typcn-archive'></td>" +
"</tr>"
);
});
//Hold user by clicking on hold modal
$(document).on("click", ".hold", function() {
var answer = window.confirm("Are You sure to mark this user as Hold?");
if (answer) {
var holdid = $(this).data("holdid");
var sts_date = $(this).closest('tr').find(".statsdate").text();
var obj = {
uID: holdid,
date: sts_date
};
var myJSON = JSON.stringify(obj);
console.log(myJSON);
} else {
$("#usersCount").html("");
}
});
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>User ID</th>
<th>Date</th>
<th>Name</th>
<th>User Status</th>
<th colspan="4" class="text-center">Action</th>
</tr>
</thead>
<tbody id="load-table">
<!-- dummy data for StackOverFlow to show you data (By the way this data is dynamic coming from a database. I have placed dummy data only to show the output. So you can ignore data in #load-table)-->
<tr>
<td>1</td>
<td class="statsdate">2022-02-12</td>
<td>Jhon</td>
<td>Active</td>
<td>
<button class="hold" data-holdid="holdid">Hold</button>
</td>
</tr>
<tr>
<td>4</td>
<td class="statsdate">2022-02-11</td>
<td>Michele</td>
<td>Active</td>
<td>
<button class="hold" data-holdid="holdid">Hold</button>
</td>
</tr>
<tr>
<td>10</td>
<td class="statsdate">2022-02-10</td>
<td>William</td>
<td>Active</td>
<td>
<button class="hold" data-holdid="holdid">Hold</button>
</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
So I have this, and what I want to get is the ID or Key from each user.
For example: WxA2XLigx7V1bOxm5WNSnVkgtOu1
And I'm currently showing this so far:
This is my current code that shows the table
firebase.database().ref('Users/').on('value',(data)=>{
let Users = data.val();
document.getElementById('tablaUsers').innerHTML+='';
for (const user in Users){
document.getElementById('tablaUsers').innerHTML+=`
<tr>
<td>${Users[user].Key}</td>
<td>${Users[user].email}</td>
<td>${Users[user].name}</td>
</tr>
`;
}
And this is the code from the html
<table class="mdl-data-table mdl-js-data-table">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric" role="columnheader" scope="col">ID</th>
<th class="mdl-data-table__cell--non-numeric" role="columnheader" scope="col">Email</th>
<th class="mdl-data-table__cell--non-numeric" role="columnheader" scope="col">Nombre</th>
</tr>
</thead>
<tbody id="tablaUsers">
<tr>
<td class="mdl-data-table__cell--non-numeric"></td>
<td class="mdl-data-table__cell--non-numeric"></td>
<td class="mdl-data-table__cell--non-numeric"></td>
</tr>
</tbody>
</table>
As you see my
<td>${Users[user].Key}</td>
Is not working, it's just a placeholder. It may be a simple problem but I canĀ“t get it or how to do it, hope anyone can help.
You should loop on the JavaScript object returned by the val() method, as follows:
firebase
.database()
.ref('users/')
.on('value', (data) => {
var obj = data.val();
Object.keys(obj).forEach((key) => {
console.log('key: ' + key);
console.log('mail: ' + obj[key].mail);
console.log('name: ' + obj[key].name);
});
});
I have an angularjs application and am using e-form to view/add/edit rows in a table. When I choose add, I would like the new row to present at the top of the list rather than the bottom of the list. Once the row is added, it should sort according to the sort order I have designed. But for usability, it's friendlier for the user if the new row is at the top of the page. Any ideas, suggestions, etc. greatly appreciated.
HTML:
<md-button type="button" class="md-accent md-raised" ng-click="searchText=undefined; addContributor()">+ Add Contributor</md-button>
</div>
</md-card-header-text><label>Search: <input ng-model="searchText"></label><button-xs ng-click="searchText=undefined">Clear</button-xs>
</md-card-header>
<md-card-content class="px-helper-pt-0">
<md-table-container>
<table md-table md-progress="vm.contributors">
<colgroup><col></colgroup>
<colgroup><col></colgroup>
<colgroup><col></colgroup>
<colgroup><col></colgroup>
<thead md-head md-order="vm.query.order">
<tr md-row>
<th ng-show=false md-column md-order-by="id" class="md-body-2"><span class="md-body-2">Id</span></th>
<th md-column md-order-by="name" class="md-body-2"><span class="md-body-2">Name</span></th>
<th md-column md-order-by="role" class="md-body-2"><span class="md-body-2">Role</span></th>
<th md-column class="md-body-2"><span class="md-body-2">Edit</span></th>
<th md-column class="md-body-2"><span class="md-body-2"></span></th>
</tr>
</thead>
<tr dir-paginate="item in vm.contributors | filter:{searchField:searchText} | itemsPerPage: 25 | orderBy: vm.query.order">
<td ng-show=false md-cell><span editable-text="item.id" e-disabled e-name="id" e-form="rowform">{{item.id}}</span></a></td>
<td md-cell><span editable-text="item.name" e-name="name" e-form="rowform">{{item.name}}</span></a></td>
<td md-cell><span editable-text="item.role" e-name="role" e-form="rowform">{{item.role}}</span></a></td>
<td style="white-space: nowrap">
<form editable-form name="rowform" onbeforesave="saveContributor($data, item.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == item">
<md-button type="submit" ng-disabled="rowform.$waiting" class="md-accent md-raised">save</md-button>
<md-button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">Cancel</md-button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<md-button type="button" class="md-primary md-raised" ng-click="rowform.$show()">edit</md-button>
<md-button class="md-warn md-raised" ng-confirm-message="Are you sure you want to delete?" ng-confirm-click="deleteContributor(item.id)">Delete</md-button>
</div>
</td>
</tr>
</table>
</md-table-container>
controller:
activate();
function activate() {
vm.promises = [getContributors()];
return $q.all(vm.promises).then(function() {
logger.info('Activation', 'Contributors Controller', 'Template Rendered');
});
}
vm.query = {
order: 'name'
};
$scope.deleteContributor = function(contributorId) {
contributorsFactory.deleteContributor(contributorId).then(function(status) {
console.log(status);
if (status !== 409) {
$mdToast.show($mdToast.simple().textContent('Deleted Contributor' + contributorId).theme('success').position('left top'));
contributorsFactory.deleteItemFromArrayById(contributorId, vm.contributors);
}
window.setTimeout(function() {window.location.reload();}, 1000);
});
};
$scope.saveContributor = function(data, id) {
contributorsFactory.updateContributor(JSON.stringify(data), id).then(function(res) {console.log(res);});
$mdToast.show($mdToast.simple().textContent('Form Saved').theme('success').position('left top'));
window.setTimeout(function() {window.location.reload();}, 1000);
};
$scope.addContributor = function() {
$scope.inserted = {
value: ''
};
vm.contributors.push($scope.inserted);
};
function getContributors() {
var item;
return dojo.contribCollection()
.then(function(data) {
vm.contributors = data;
angular.forEach(vm.contributors, function(e) {
e.searchField = e.id + ' ' + e.name + ' ' + e.role + ' ';
If you want new item display in the first . You can try use splice
vm.contributors.splice(0,0,itemyouwanpush)
And why you mixing $scope with controllerAs? Just use one . In html you change ng-click to
vm.addContributor()
And in controller
vm.addContributor()=function(){
vm.contributors.splice(0,0,itemyouwanpush)
}
And dont forget
var vm = this; in controller
This is the code that resolved the issue:
controller.js
vm.contributors.splice(0, 0, $scope.inserted = {name: '', role: ''});
I have table with empty body:
<table id="tablem" border="1" width="100">
<thead>
<tr>
<th style="width: 10%">PageName</th>
<th style="width: 5%">Lang</th>
<th style="width: 10%">ControlName</th>
<th style="width: 70%">ControlValue</th>
<th style="width: 5%">Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I fill body by AJAX-request, which gets data from the database, and this Ajax-function construct table's body with data:
function ForSearching(args, callback) {
$.ajax({
url: "/source_pages/SearchForMultilang.ashx",
type: "POST",
dataType: "json",
data: args,
}).success(function(data) {
var table = $("#tablem tbody");
$("#tablem tbody").empty();
callback(data);
$.each(data, function (idx, elem) {
table.append('<tr><td>' + elem.PageName + '</td><td>' + elem.Lang + '</td><td>' + elem.ControlName + '</td><td>' + elem.ControlValue + '</td><td><input type="button" id="btnedt" value="Edit" /></td></tr>');
});
});
}
The table is created, filled by data, and in the last column Ajax creates Edit-button.
When you click this button, textfield in every column in row must transform to input type=text with value from cell, so I can change value and after all save this changes in the selected row. And all this must work by ajax.
How to do this?
I recommend to put this code witch changed selector in click handler of this button
$('td').each(function(){
$(this).html($('<input>',{type:'text', value: $(this).html()}));
});
https://jsfiddle.net/urp83mtq/1/
EDIT: I just saw that you want have one button per row
$(':button').each(function(){
$(this).on('click',function(){
$(this).parent().parent().children().each(function(){
if($(this).children().length==0)
$(this).html($('<input>',{type:'text', value: $(this).html()}));
});
});
});
https://jsfiddle.net/urp83mtq/2/
I have a ViewModel works with knockout framework and ajax. I can save new items to the database with ajax.Save but I have problem when I want to retrieve the saved data. Here are the codes.
Codes in ViewModel:
self.Categories = ko.observableArray([]);
self.Message = ko.observable("");
elf.GetCategories = function () {
$.ajax({
url: "/Admin/Categories",
cache: false,
type: "GET",
datatype: "json",
contenttype: "application/json;utf8"
}).done(function (data) {
self.Categories(ko.mapping.fromJS(data));
}).error(function (err) {
self.Message("Error! " + err.status);
});
}
console.log(JSON.stringify(data)); returns:
{"categories":[{"Id":1,"Name":"Learning","UrlSlug":"0-learning","Description":"learning"},
{"Id":2,"Name":"Topics","UrlSlug":"0-topics","Description":"posts"},
{"Id":3,"Name":"Shares","UrlSlug":"category-shares","Description":"shares"},
{"Id":4,"Name":"Projects","UrlSlug":"category-projects","Description":"project"}]}
Codes in controller is:
[HttpGet]
public ContentResult Categories()
{
var categories = _weblogServices.Categories();
return Content(JsonConvert.SerializeObject(new {categories}), "application/json;utf8");
}
and the problem is the self.Categories = ko.observableArray([]); is always empty without any data. I also tried these items too, but nothing changed:
ko.mapping.fromJS(data, self.Categories);
self.Categories(ko.mapping.fromJS(data));
self.Categories(ko.mapping.fromJSON(data));
ko.mapping.fromJS(data, {}, self.Categories);
I have a simple table in view :
<table id="tblCategory" class="table table-striped table-bordered
table-responsive table-condensed table-hover">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Url Slug</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody data-bind="foreach: Categories">
<tr>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: UrlSlug"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><button type="button" class="btn glyphicon glyphicon-pencil"
title="Edit" data-bind="click:$data.GetSelected"></button></td>
<td><button type="button" class="btn glyphicon glyphicon-trash"
title="Delete" data-bind="click:$data.DeleteSelectedCategory">/button></td>
</tr>
</tbody>
</table>
So, the question is how can I convert JSON data to observableArray([])?
UPdate: Chrome debugger says: data and Categories are not available.
You don't need to use mapping at all.
In your ajax call .done, you simply have to do this:
self.categories(data.categories);
As an observable array, categories expect an array as parameter. And according to the result of console.log(JSON.stringify(data)) being: {"categories":[{...}, {...}, ...], the array is on the categories property of the received data.
You don't need to use mapping because you simply need to show the objects inside the array, and you don't want to edit their properties. So they can be left as regular JavaScript objects, without observable properties.