I'm trying to display the data in the table depending on search. How can I achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" value="submit">
Expected o/p:
search any field ex:
input: java,
output :john and jane profiles
input:sql
output: only jane profile //he is the person who has sql skill
if nothing matches show 0 results
User can search using any one field, if any one item matches that profile should be displayed in my table. How can I do this? Can anyone please help me sort it out?
/* Dataset*/
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for(i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
console.log(getResult()); // print expected data
});
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
in ES6 you can do it :
results = array.filter (x=>x.username.search(search_txt));
let my_list = [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"},{"username":"Chuck Berry","email":"cb#gmail.com","skills":"vuejs"}];
results = my_list.filter (x => x.skills.search('java')!=-1);
console.log(results);
//result is : [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"}]
<!DOCTYPE html>
<html>
<head>
<title>SEARCH</title>
</head>
<body>
<input type="text" placeholder="skills" id="skills">
<input type="email" placeholder="mail id" id="email">
<input type="text" placeholder="username" id="username">
<input type="submit" value="submit" id="submit">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Skills</th>
</tr>
<tr id="search">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
$('#submit').click(function(){
var skills = $('#skills').val();
var email = $('#email').val();
var username = $('#username').val();
if(username){
search(username);
}
});
function search(username){
var name = username;
var html ;
data.forEach(function(currentValue, index, array){
if(currentValue.username == name){
html = "<td>"+currentValue.username+"</td>"+
"<td>"+currentValue.email+"</td"+
"<td>"+currentValue.skills+"</td>"
;
}else{
html = "Result Not Found";
}
});
return $('#search').html(html);
}
</script>
</body>
</html>
You can make a search function for skills like this:
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
var skills = "java,c";
function search(){
result = [];
var setSkills = skills.split(","); console.log(setSkills);
data.map((current,index)=>{
let currentSkills = current.skills.split(","); //console.log(currentSkills);
// currentSkills = ["java", "c", "html", "css"]
// setSkills = ["java", "c"] ;
// length of set currentSkills == length of set (currentSkills + setSkill) --> mean setSkills is subset of currentSkills
let bool = Array.from(new Set(currentSkills) ).length == Array.from(new Set(currentSkills.concat(setSkills)) ).length;
if(bool)
console.log(data[index]);
});
}
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" onclick="search();" value="submit">
Related
I am working on a simple form that is sending data to a customers lead management database via their API. The form returns a 400 error when their is a duplicate email entered into the system. When this or other issues happen I need to be able to throw an error in the console and log the error in a text file within my Wordpress Child theme. I can not seem to get the error to report in the console as well as how to send the error to a txt file. If the form submits okay then everything works, I get a 200 and the lead goes in. Here is what I have so far:
<form class="mbform" id="base_form" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post">
<div class="field">
<input for="base_form" id="first-name" type="text" name="base_fname" placeholder="First Name*" required><br>
</div>
<div class="field">
<input for="base_form" id="last-name" type="text" name="base_lname" placeholder="Last Name*" required><br>
</div>
<div class="field">
<input for="base_form" id="email" type="text" name="base_email" placeholder="Email*" required><br>
</div>
<div class="field">
<input for="base_form" id="phone" type="tel" pattern="[(]\d{3}[)][\s]\d{3}[\-]\d{4}" name="base_phone" placeholder="Mobile*" required><br>
</div>
<input type="hidden" name="action" value="custom_action">
<div class="field submit-button">
<button class="button mbgo" for="base_form" type="submit" name="base_submit">Claim Offer</button>
</div>
</form>
<script>
jQuery(document).ready(function($) {
$('#base_form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var settings = {
"url": "https://apiendpoint.com/api/WorkOrder/PostAllWorkOrder",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Bearer jTs1OCFtj5HRhYJmqRjbO35F0x0BnAmyV05hTLUzZjTbXWbfvmhhDXCp4oU8Zg9_Ec6z34n5nkCQOLRMPsK4JnM_NZiVFJGf6DRxkWQt4DzOfFhT06q2KalQrrmA5WoykVLLIE5RR8A1m34TUK37gh4E08zwC3hwW4rnQfIhez30MLDCR-PWEXTfhP5DugjzCrzoR05B15ggXt3OxoRNKxeWgcCw6Q6-E5Cl6Wlkge5iiH3DKoUqAn2tJ1m2UlXobWXSG86o3yfQsPfI7966Uy5zGU7UGB4RTD-Cz8I2U2PC7a4L-TK6UbAem2d2zfusYor81iuMcHfRCsZm60YCtGfbatuYxGXe7HCHmH6mtU8S-aGPJFhpdcyjsa7lx44_KhYzR6EsnKixgu26Wu-qnHmbKaBBKDdqZBMxrJo4tNVM9772WfjdNQpKIDfytZCWQj-iyhmerqdg9mIt3v9Ez79LKliPXXhFkgoESECKhMaHUNLX",
"Content-Type": "application/json",
"Cookie": ".AspNet.Cookies=3iF1xtlsAqyPyTxheHIYgFkvYtepDaZk8UnqLYbkezCdSGVSFCaQwl_9JqTJ8UJ8ytHZ5zrS-vwc3bkbwbJjjZdjn6gRKAMuUG6S2ANvUX94GoIC0-RGW_gXbr2aA-Qle4f8KnPRFKF0BEIBV0Kacxk51u7wBOyJiR7XGSVfrNq5F-fVTAnkrX4o8S0YLm7HC8WhyLgGMlpy6IhmXUplvwMbeQ7y9ZkSizGl9ETrYSr4vYP3tj7hAS-JCvsXm_UaI705bl_lo_iFdbrKaTAN9CONVV-KV1WpmGx-n3J__731wyr20_V1pBy4szbZ2rXych_Ik-b2kiVhj3zikE7q4iiL4k8wD8DiFHYQC_DnqbwFG0hKqs-YU5EEb-0TYSW3mChFUbVVJpEiJ5wxYpmO8Lni9JsNTf_baf-_QYWVRXaE5P5vnfN9gJHIm3Me6oFdvpo3YIPSm6Yci--LDUVeiLtTg10"
},
"data": {
"FRANCHISEID": 1,
"WSTicketNumber": "487260",
"SERVICETYPEID": 0,
"LeadSourceId": "1",
"Note": "N/A",
"IsLeadOnly": true,
"Customer": {
"FirstName": jQuery("#first-name").val(),
"LastName": jQuery("#last-name").val(),
"Address": null,
"Address2": null,
"City": null,
"State": null,
"PostalCode": null,
"Email": jQuery("#email").val(),
"Phone": jQuery("#phone").val(),
"PhoneType": "Cell Phone",
"PreferredCommunicationType": "phone",
"MemberSecondaryIndexCode": "50"
}
}
};
var allData = settings.data.Customer;
$.ajax(settings).done(function (response) {
console.log(response);
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
});
$.ajax(settings).fail(function (response) {
console.log(response);
console.log(allData);
var message = allData.FirstName;
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>There was an issue with your recent submission</h2>")
.append("<p>" + message + "</p>")
});
});
$("input[name='base_phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1) $2-$3"));
});
});
</script>
Consider the following.
jQuery(document).ready(function($) {
$('#base_form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var settings = {
"url": "https://apiendpoint.com/api/WorkOrder/PostAllWorkOrder",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Bearer jTs1OCFtj5HRhYJmqRjbO35F0x0BnAmyV05hTLUzZjTbXWbfvmhhDXCp4oU8Zg9_Ec6z34n5nkCQOLRMPsK4JnM_NZiVFJGf6DRxkWQt4DzOfFhT06q2KalQrrmA5WoykVLLIE5RR8A1m34TUK37gh4E08zwC3hwW4rnQfIhez30MLDCR-PWEXTfhP5DugjzCrzoR05B15ggXt3OxoRNKxeWgcCw6Q6-E5Cl6Wlkge5iiH3DKoUqAn2tJ1m2UlXobWXSG86o3yfQsPfI7966Uy5zGU7UGB4RTD-Cz8I2U2PC7a4L-TK6UbAem2d2zfusYor81iuMcHfRCsZm60YCtGfbatuYxGXe7HCHmH6mtU8S-aGPJFhpdcyjsa7lx44_KhYzR6EsnKixgu26Wu-qnHmbKaBBKDdqZBMxrJo4tNVM9772WfjdNQpKIDfytZCWQj-iyhmerqdg9mIt3v9Ez79LKliPXXhFkgoESECKhMaHUNLX",
"Content-Type": "application/json",
"Cookie": ".AspNet.Cookies=3iF1xtlsAqyPyTxheHIYgFkvYtepDaZk8UnqLYbkezCdSGVSFCaQwl_9JqTJ8UJ8ytHZ5zrS-vwc3bkbwbJjjZdjn6gRKAMuUG6S2ANvUX94GoIC0-RGW_gXbr2aA-Qle4f8KnPRFKF0BEIBV0Kacxk51u7wBOyJiR7XGSVfrNq5F-fVTAnkrX4o8S0YLm7HC8WhyLgGMlpy6IhmXUplvwMbeQ7y9ZkSizGl9ETrYSr4vYP3tj7hAS-JCvsXm_UaI705bl_lo_iFdbrKaTAN9CONVV-KV1WpmGx-n3J__731wyr20_V1pBy4szbZ2rXych_Ik-b2kiVhj3zikE7q4iiL4k8wD8DiFHYQC_DnqbwFG0hKqs-YU5EEb-0TYSW3mChFUbVVJpEiJ5wxYpmO8Lni9JsNTf_baf-_QYWVRXaE5P5vnfN9gJHIm3Me6oFdvpo3YIPSm6Yci--LDUVeiLtTg10"
},
"data": {
"FRANCHISEID": 1,
"WSTicketNumber": "487260",
"SERVICETYPEID": 0,
"LeadSourceId": "1",
"Note": "N/A",
"IsLeadOnly": true,
"Customer": {
"FirstName": jQuery("#first-name").val(),
"LastName": jQuery("#last-name").val(),
"Address": null,
"Address2": null,
"City": null,
"State": null,
"PostalCode": null,
"Email": jQuery("#email").val(),
"Phone": jQuery("#phone").val(),
"PhoneType": "Cell Phone",
"PreferredCommunicationType": "phone",
"MemberSecondaryIndexCode": "50"
}
}
};
var allData = settings.data.Customer;
var request = $.ajax(settings).done(function(response) {
console.log(response);
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
});
request.fail(function(response) {
console.log(response);
console.log(allData);
var message = allData.FirstName;
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>There was an issue with your recent submission</h2>")
.append("<p>" + message + "</p>")
});
});
$("input[name='base_phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1) $2-$3"));
});
});
This will Assign handlers immediately after making the request, and remember the jqXHR object for this request.
See More: https://api.jquery.com/jquery.ajax/
How to display json data in html table using jQuery ? and How can i remove case sensitive while searching the result?
expected output
How can i display the result in my table? How can i achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (
data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
You need to create a table and need to append coming data to this table using below code:-
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
To do case-insensitive comparison use .toUpperCase()
Working snippet:-
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]["email"].toUpperCase() === email.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<br>
<table>
<thead>
<tr>
<th>Username</th>
<th>Email ID</th>
<th>Core Skills</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can use Data-table jQuery plugin to generate table from jsondirectly like
$('#tableId').DataTable({
data: jsonData,
columns: [
{ data: 'username',title:'Username'},
{ data: 'emailId',title:'EmailId'},
{ data: 'skils',title:'Core Skills'}
],
"search": {
"caseInsensitive": false
}
});
For More detail follow Data-table jQuery Plugin.
Here is the code
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
function BindDataToTable(d,obj){
var keys=Object.keys(d[0]);
var table=document.createElement("table");
var trHead=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var th=document.createElement("th");
th.innerHTML=item;
trHead.appendChild(th)
})
table.appendChild(trHead)
for(var i=0;i<d.length;i++){
var tr=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var td=document.createElement("td");
td.innerHTML=d[i][item];
tr.appendChild(td)
})
table.appendChild(tr)
}
jQuery(obj).append(table);
}
BindDataToTable(data,"#tableElement")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<div id="tableElement">
</div>
I am using toggle class for highlighting table cells.
<style>
table td.highlighted {
background-color: #999;
}
</style>
<script>
$(function () {
var isMouseDown = false;
$("#productTable td")
.mousedown(function () {
isMouseDown = true;
debugger;
$(this).toggleClass("highlighted");
return false; // prevent text selection
});
$(document)
.mouseup(function () {
debugger;
isMouseDown = false;
});
});
</script>
And my table is like this:
<div class="container">
<div class="row">
<form>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-search"></i>
</div>
<input type="text" class="form-control" placeholder="Aramak İstediğiniz Ürün Alanını Giriniz" ng-model="src_product">
</div>
</div>
</form>
</div>
<div class="row">
<div class="col-md-10">
<br />
<table ng-table="usersTable" id="productTable" class="table table-striped">
<tr>
<th ng-repeat="column in cols">{{column}}</th>
<th> Adet</th>
</tr>
<tr ng-repeat="row in data | filter: src_product">
<td id="productProperties" ng-model="productProperties" ng-repeat="column in cols ">{{row[column]}}</td>
<td><input type="text" style="width: 100%; height: 30px !important" name=" adet" value="0"></td>
</tr>
</table>
</div>
</div>
</div>
this is my controller:
myApp.controller('productController', ['$rootScope', '$scope', 'SharedDataService', "productFactory", "$log", "$filter", 'ngTableParams', function ($rootScope, $scope, SharedDataService, productFactory, $log, $filter, ngTableParams) {
$scope.users = [{"id":1,"first_name":"Philip","last_name":"Kim","email":"pkim0#mediafire.com","country":"Indonesia","ip_address":"29.107.35.8"},
{"id":2,"first_name":"Judith","last_name":"Austin","email":"jaustin1#mapquest.com","country":"China","ip_address":"173.65.94.30"},
{"id":3,"first_name":"Julie","last_name":"Wells","email":"jwells2#illinois.edu","country":"Finland","ip_address":"9.100.80.145"},
{"id":4,"first_name":"Gloria","last_name":"Greene","email":"ggreene3#blogs.com","country":"Indonesia","ip_address":"69.115.85.157"},
{"id":50,"first_name":"Andrea","last_name":"Greene","email":"agreene4#fda.gov","country":"Russia","ip_address":"128.72.13.52"},{"id":1,"first_name":"Philip","last_name":"Kim","email":"pkim0#mediafire.com","country":"Indonesia","ip_address":"29.107.35.8"},
{"id":2,"first_name":"Judith","last_name":"Austin","email":"jaustin1#mapquest.com","country":"China","ip_address":"173.65.94.30"},
{"id":3,"first_name":"Julie","last_name":"Wells","email":"jwells2#illinois.edu","country":"Finland","ip_address":"9.100.80.145"},
{"id":4,"first_name":"Gloria","last_name":"Greene","email":"ggreene3#blogs.com","country":"Indonesia","ip_address":"69.115.85.157"},
{ "id": 50, "first_name": "Andrea", "last_name": "Greene", "email": "agreene4#fda.gov", "country": "Russia", "ip_address": "128.72.13.52" },
{ "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "pkim0#mediafire.com", "country": "Indonesia", "ip_address": "29.107.35.8" },
{ "id": 2, "first_name": "Judith", "last_name": "Austin", "email": "jaustin1#mapquest.com", "country": "China", "ip_address": "173.65.94.30" },
{ "id": 3, "first_name": "Julie", "last_name": "Wells", "email": "jwells2#illinois.edu", "country": "Finland", "ip_address": "9.100.80.145" },
{ "id": 4, "first_name": "Gloria", "last_name": "Greene", "email": "ggreene3#blogs.com", "country": "Indonesia", "ip_address": "69.115.85.157" },
{ "id": 50, "first_name": "Andrea", "last_name": "Greene", "email": "agreene4#fda.gov", "country": "Russia", "ip_address": "128.72.13.52" }];
$scope.usersTable = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.users.length,
getData: function ($defer, params) {
$scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
$scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
$scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.data);
}
});
$scope.cols = Object.keys($scope.users[0]);
$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
debugger;
$scope.idSelectedVote = idSelectedVote;
};
$scope.src_product = '';
}]);
My table is looking like this:
Here is the my question. when i search a word or go second page of table highlighted cells are turn back non highligted and it doesnt let me select a cell. How can i do stable cells and take highlighted cells values ?
On page change or search, the table is redrawn so your class change is lost. If you assign the class based on a model value, you could instead change the model value and get the class modified, and this would be persisted across redraws. You can use ng-class attribute to make the class name used for the td dependant on a model value. For example:
<td ng-class="{'highlighted':row[column].isSelected}" ng-click="selectCell(row[column])"></td>
Then, inside your controller, you can create a function:
$scope.selectCell = function(cell) {
typeof cell.isSelected === "undefined" ? cell.isSelected = true : cell.isSelected = false;
}
ngClass
ngClick
When i tried to click the edit radio button the details will be displayed in the concerned boxes but the existing details in the table is deleted. Here my requirement is to use single array/scope variable for edit, display and delete. But no use for loop while edit/delete. Here i done the changes but no proper way of work. my html index.html as follows
<div ng-controller="employeeController">
<header><h1>Employee Details</h1></header>
<form name="myForm" novalidate>
<table id="myTable" cellspacing="0" cellpadding="4">
<tr>
<td><label> Employee Id </Label></td>
<td><input type="text" name="eid" data-ng-model="employees.EmployeeId" data-ng-required="true" ng-disabled="newEmployees"/></td>
</tr>
<tr>
<td><label> FirstName </Label></td>
<td><input type="text" name="fname" data-ng-model="employees.FirstName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> LastName </Label></td>
<td><input type="text" name="lname" data-ng-model="employees.LastName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Gender </Label></td>
<td>
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Male" data-ng-model="employees.Gender"/> Male
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Female" data-ng-model="employees.Gender"/>Female
</td>
</tr>
<tr>
<td><label> Email </Label></td>
<td><input type="text" name="email" data-ng-model="employees.Email" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Account </Label></td>
<td><input type="text" name="account" data-ng-model="employees.Account" data-ng-required="true"/></td>
</tr>
<tr>
<td><input type="hidden" data-ng-model="employees.EmployeeId"></td>
</tr>
</table>
<button name="btnSave" data-ng-click="saveEmployeeRecord(employees)" class="userbutton">Save</button>
<button name="btnReset" data-ng-click="resetEmployeeRecord()" class="userbutton">Reset</button>
</form>
<table border="2" cellspacing="0" cellpadding="4">
<tr style="color: blue">
<th style="width:100px">Employee Id</th>
<th style="width:150px">FirstName</th>
<th style="width:150px">LastName</th>
<th style="width:90px">Gender</th>
<th style="width:150px">Email</th>
<th style="width:60px">Account</th>
<th>Action</th>
</tr>
<tr style="color:green" data-ng-repeat="emp in employees">
<td>{{emp.EmployeeId}}</td>
<td>{{emp.FirstName}}</td>
<td>{{emp.LastName}}</td>
<td>{{emp.Gender}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Account}}</td>
<td>
<input type="radio" name="process" data-ng-click="editEmployee(emp, employees.indexOf(emp))"> Edit
<input type="radio" name="process" data-ng-click="DeleteEmployee(employees.indexOf(emp))"> Delete
</td>
</tr>
</table>
</div>
javascript app.js
var employeeApp = angular.module("myApp",[]);
employeeApp.controller("employeeController", function($rootScope, $scope, $http) {
$http.get('data/employees.json').success(function(data) {
$rootScope.employees = data;
});
var empId = 12342;
$rootScope.saveEmployeeRecord = function(emp) {
if($rootScope.employees.EmployeeId == null) {
$rootScope.employees.EmployeeId = empId++;
$rootScope.employees.push(emp);
}
else {
for(i in $rootScope.employees) {
if($rootScope.employees[i].EmployeeId == emp.EmployeeId) {
$rootScope.employees[i]= emp;
}
}
}
//$rootScope.employees = {};
}
$rootScope.resetEmployeeRecord = function() {
angular.copy({}, $rootScope.employees);
}
$rootScope.editEmployee = function(emp, indx) {
//$rootScope.emp = $rootScope.employees;
if($rootScope.employees[indx].EmployeeId == emp.EmployeeId) {
$rootScope.employees = angular.copy($rootScope.employees[indx]);
}
}
$rootScope.DeleteEmployee = function(idx) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(idx,1);
return true;
}
else {
return false;
}
//for(i in $rootScope.employees) {
//if($rootScope.employees[i].EmployeeId == idx) {
//$rootScope.employees = {};
//}
//}
}
});
employees.json file:
[
{
"EmployeeId": "61234",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james_anderson#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "512458",
"LastName": "Cambell",
"FirstName": "Mike",
"Gender": "Male",
"Email": "mike.cambell#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "712785",
"LastName": "Swachengar",
"FirstName": "Andrew",
"Gender": "Male",
"Email": "andrew.swachengar#infosys.com",
"Account": "Cisco"
},
{
"EmployeeId": "712734",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james.anderson#infosys.com",
"Account": "Apple"
},
{
"EmployeeId": "61245",
"LastName": "Green",
"FirstName": "Rachael",
"Gender": "Female",
"Email": "rachael_green#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "61347",
"LastName": "Brown",
"FirstName": "Jackualine",
"Gender": "Female",
"Email": "jackualine_brown#infosys.com",
"Account": "Boeing"
}
]
You need to assign the selected item to a model which you have to associate in your edit/save form. And then when "save" is clicked, you need to update the original data with the updated data. Here's an example of how that would work:
$rootScope.saveEmployeeRecord = function() {
for(k in $scope.selectedEmployee){
$scope.selectedEmployee[k] = $scope.selectedEmployeeCopy[k];
}
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
}
$rootScope.editEmployee = function(emp) {
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
Here, I am making a copy of your original employee, and updating the copy. When saved, the copy will replace the original employee. When cancelled, it will be simply ignored. Here's a working fiddle based on your code.
Edit: based on feedback, updated the save and delete method which were not working as expected. Also updated the jsFiddle.
Edit2: Removed for loops and relpaced with passing array index
$rootScope.saveEmployeeRecord = function() {
$rootScope.employees.splice($rootScope.selectedIndex, 1,$rootScope.selectedEmployeeCopy);
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
}
$rootScope.editEmployee = function(emp, ind) {
$rootScope.selectedIndex = ind;
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
$rootScope.DeleteEmployee = function(emp, ind) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(ind, 1);
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
return true;
}
else {
return false;
}
}
You can Pass id as like this with your index in your radio button.
<button class="btn btn-default" ng-click="editBook(add.id, $index);" type="submit">Edit</button>
See my controller:
$scope.editBook = function(id,index) {
$scope.show1=false;
$scope.show=true;
$http.get(appurl + 'user/adds/' + id + '.json')
.success(function(data, status, headers, config) {
$scope.user= data;
angular.copy($scope.user, $scope.copy);
});
};
I followed a video tutorial but I failed to output the result regardless many hours works. The output I expect is when user type some name to search for a company for example, companies' name will be show as a suggestion list. After select a certain company, more details of the company will be shown such as location, opening hours. I attach my HTML, JavaSCript and example JSON file here.
<body>
<div id="searcharea">
<label for="search">Ajax search</label>
<p> enter the name </p>
<input type="search" name="search" id="search" placeholder="company
name" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
$(#search).keyup(function() {
var searchFiled = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('mylist.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
if (val.user.search(myExp) != -1) {
output += '<li>';
output += '<h2>' + val.company + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('$update').html(output);
});
});
{
"data": [{
"user_id": "1",
"name": "Lala",
"address": "somewhere on the world",
"company": "big company",
}, {
"user_id": "2",
"name": "Tom",
"address": "USA",
"company": "CocaCola",
}]
"reminds": 0,
"message": "this is a message",
"myID": 0
}