the below code works great for displaying in my first file
$.ajax({
url : "http://localhost/website/files/userstuff/files/",
asynch : false,
cache : false,
success: function (data) {
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("#filestable").html(displayfilestable)
$("filestable, table").append(adddata);
console.log(adddata)
}
});
}
});
this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance
enter image description here
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.
HTML
<div>
sad1.pdf<br>
sad2.pdf<br>
sad3.pdf
<div id="filestable"></div>
</div>
JAVASCRIPT
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("filestable, table").append(adddata);
console.log(adddata)
}
});
AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/
Related
I have a bootstrap live search for pixabay api. But I have a problem with results from pixabay.
For example, I want to search images with query flowers but its returning results when i start typing. I type flo and i have a images with tag flo.
At the end I have links to images with tag flow flowe and flowers.
How to prevent this situation?
$('#search').keyup(function(){
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(q);
$.getJSON(URL, function(data){
if (parseInt(data.totalHits) > 0)
$.each(data.hits, function(i, hit){
htmlData = '<div class="col"><img src="'+hit.largeImageURL+'" class="img-fluid" alt=""/></div>';
$('.modal-body').append(htmlData);
});
else
console.log('No hits');
});
});
How to load expected images dynamically into modal?
Also how to remove images when i remove few chars from search bar?
If i put flowers It load flowers into modal, but when i type cars I want to show only cars, not flowers and cars.
There's two things you need to do to fix this behaviour. The first is to 'debounce' the event so that the AJAX request is only made when typing has finished for a short delay, eg. 150ms. The second is to wipe all previous results from the UI before you add the latest ones. Try this:
var searchTimeout;
$('#search').keyup(function() {
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key=" + API_KEY + "&q=" + encodeURIComponent(q);
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
$.getJSON(URL, function(data) {
if (parseInt(data.totalHits) > 0) {
var htmlData = data.hits.map(function(hit) {
return `<div class="col"><img src="${hit.largeImageURL}" class="img-fluid" alt=""/></div>`;
});
$('.modal-body').html(htmlData); // note 'html()' here. It will overwrite all existing content
} else {
console.log('No hits');
}
});
}, 150);
});
I am trying to link my HTML form with my csv file to populate form field automatically. Based on what user selects in first field, second field should be automatically filled with the appropriate value. when the user starts typing in the first field, the input field automatically pulls data from csv file to show available options. Options appear after user completes writing 3 words in the field.
Further, to avoid any CORS issue in code, I have added additional URL in my CSV file URL which makes it accessible by any web application.
I was able to prepare this code with the help of examples available on web. However, my code is not working properly. I tried to solve this problem on my own. But I don't know about coding enough.
Can anyone please help me to solve this problem.
<script>
$(function() { function processData(allText) { var record_num = 2;
// or however many elements there are in each row
var allTextLines = allText.split(/\r\n|\n/); var lines = []; var headings = allTextLines.shift().split(','); while (allTextLines.length > 0) { var tobj = {}, entry; entry = allTextLines.shift().split(','); tobj['label'] = entry[0]; tobj['value'] = entry[1]; lines.push(tobj); } return lines; }
// Storage for lists of CSV Data
var lists = [];
// Get the CSV Content
$.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt ", function(data) { lists = processData(data); }); $("#species").autocomplete({ minLength: 3, source: lists, select: function(event, ui) { $("#species").val(ui.item.label); $("#identifiant").val(ui.item.value); return false; } }); });)
</script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<form>
<div class="ui-widget"> <label for="species">Species: </label> <input id="species"> <label for="identifiant">Identifiant: </label> <input id="identifiant" style="width: 6em;"> </div></form>
Here's the modified answer, working with jquery-ui autocomplete.
The solution: the $.get() is an asynchronous function (the data is not readily available on page load), so jquery-ui autocomplete didn't work with the updated lists[] array, because it (seems so that it) doesn't work with dynamically generated data. So the source of autocomplete had to be refreshed with the newly arrived data in the $.get()'s callback function.
$("#species").autocomplete('option', 'source', lists) - this is the key line, as it updates autocomplete's source with the new data.
// Only needed for working example
var myCSV = "Species,Identifiant\r\n";
myCSV += "Species A,320439\r\n";
myCSV += "Species B,349450\r\n";
myCSV += "Species C,43435904\r\n";
myCSV += "Species D,320440\r\n";
myCSV += "Species E,349451\r\n";
myCSV += "Species F,43435905\r\n";
console.log(myCSV);
// Begin jQuery Code
$(function() {
function processData(allText) {
// var record_num = 2; // or however many elements there are in each row
var allTextLines = allText.split(/\r\n|\n/);
var lines = [];
var headings = allTextLines.shift().split(',');
while (allTextLines.length > 0) {
var tobj = {},
entry;
entry = allTextLines.shift().split(',');
/*
Normally we'd read the headers into the object.
Since we will be using Autocomplete, it's looking for an array of objects with 'label' and 'value' properties.
tobj[headings[0]] = entry[0];
tobj[headings[1]] = entry[1];
*/
if (typeof entry[1] !== 'undefined') {
let prefix = !entry[0].includes('Species') ? 'Species ' : ''
tobj['label'] = prefix + entry[0];
tobj['value'] = entry[1].trim();
lines.push(tobj);
}
}
return lines;
}
let lists = [];
// For working example
// lists = processData(myCSV);
// console.log('lists1', lists)
// In your script you will get this content from the CSV File
// Get the CSV Content
$.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt", function(data) {
lists = processData(data);
$("#species").autocomplete('option', 'source', lists)
console.log('lists2', lists)
});
$("#species").autocomplete({
minLength: 3,
source: lists,
focus: function(event, ui) {
console.log(ui)
$("#species").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#species").val(ui.item.label);
$("#identifiant").val(ui.item.value);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<div class="ui-widget">
<label for="species">Species: </label>
<input id="species">
<label for="identifiant">Identifiant: </label>
<input id="identifiant" style="width: 6em;">
</div>
The processData() function didn't work as expected with the source you provided, so that had to be modified too.
My solution is a kinda' autocomplete - it's called typeahead.
I displayed the filtered list, so you see what's happening, but you can place that anywhere - in a dropdown below the input field, for example.
$(function() {
// processing CSV data
function processData(allText) {
// splitting lines
var allTextLines = allText.split(/\r\n|\n/);
const speciesData = []
// reading data into array, if it's not the first row (CSV header) AND
// if it's not 'Species'
let j = 0; // this will be the item's index
for (let i = 0; i < allTextLines.length - 1; i++) {
if (i !== 0 && allTextLines[i] !== 'Species') {
const record = allTextLines[i].split(',')
speciesData.push({
label: record[0],
value: record[1].trim(), // it has a lot of whitespace
index: j // adding this, so we can keep track of items
})
j++; // incrementing index
}
}
// returning processed data
return speciesData;
}
// Storage for lists of processed CSV Data
let lists = [];
// Get the CSV Content
$.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt ", function(data) {
// making processed data availabel app-wide
lists = processData(data);
// filling the 'suggestions list' the first time
suggestionListHtml(lists, $('.suggestions-container'))
});
// actions on input field input event
// only the third param differs in filterSpecies()
$('#species').on('input', function(e) {
const filteredList = filterSpecies($(this).val(), lists, 'label')
suggestionListHtml(filteredList, $('.suggestions-container'))
})
$('#identifiant').on('input', function(e) {
const filteredList = filterSpecies($(this).val(), lists, 'value')
suggestionListHtml(filteredList, $('.suggestions-container'))
})
// clicking on an item in the 'suggestions list' fills out the input fields
$('.suggestions-container').on('click', '.suggestion', function(e) {
const item = lists[$(this).attr('data-listindex')]
$('#species').val(item.label)
$('#identifiant').val(item.value)
})
});
function suggestionListHtml(filteredList, container) {
// creating HTML template for the 'suggestions list'
let html = ''
filteredList.forEach(item => {
html += `<span class="suggestion" data-listindex="${item.index}">label: ${item.label} - value: ${item.value}</span>`
})
// modifying the displayed 'suggestions list'
container
.empty()
.append(html)
}
// filtering the processed list
// #param substr - the text from the input field
// #param list - the list to be filtered
// #param attr - one of the keys in the processed list (label or value)
function filterSpecies(substr, list, attr) {
// doing the actual filtering
const filteredList = list.filter(item => {
return item[attr].toLowerCase().includes(substr.toLowerCase())
})
return filteredList
}
.suggestions-container span {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ui-widget">
<label for="species">Species: </label>
<input id="species">
<label for="identifiant">Identifiant: </label>
<input id="identifiant" style="width: 6em;">
</div>
<div class="suggestions-container">
</div>
</form>
I have a .aspx file working on SharePoint.
We are using IE11, jQuery 2.2.3, jQuery UI 1.11.4, Bootstrap 3.3.6
We had this system for around three years by a third party, which we stopped business. And not able to contact anymore.
It was working fine until a few weeks ago suddenly the page is loading forever and showing this error
SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference
Loading page - capture
I have Googled and it seems like the script is waiting for ConfigurationCube.js to load. But since it's not loading, I think it's waiting forever.
/* handles the displaying of all outstanding items requiring approval*/
var TableCreated=0;
var app="";
var teamsArr = [];
var GlobalDivisionsArr = [];
$(document).ready(function(){
//check to see if the Configuration cube Obj Exists and wait until it does
var checkExist = setInterval(function() {
if (sessionStorage["ConfigurationCube"] != null) {
app = JSON.parse(sessionStorage.ConfigurationCube).AppURL;
/**CreateLookupSectionForEmployees("My Winners","Kaizen List","#ViewWinnersTable");**/
//Displayed using the configuration cube.js file
DisplayUserInformation();
popDD("kznSearchCategory",JSON.parse(sessionStorage.ConfigurationCube).ListOfCategories);
IntialPopulationOfApprovedKaizens("","Kaizen List","#kznSearchResultsTable");
//Initialize date range picker
/**$("#kznEditToDate").datepicker();*/
var CubeMin = (JSON.parse(sessionStorage.ConfigurationCube).SubmissionPeriod).split(" ")[0];
clearInterval(checkExist);
}
}, 500);
});
I also tried in IE8, 9, 10, Edge. All not working.
Our company does not allow Chrome or any other browser so we need to get it work in IE..
My current meta tag is like this. Also tried various ways, but did not work.
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
Does anyone have any similar problems?
Any kind of idea is appreciated..
When clicking on the error, it directs to ConfigutationCube.js
//Tools for other pages
function compareStrings(a, b) {
// Assuming you want case-insensitive comparison
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
Script snip from SearchKaizen.js
function IntialPopulationOfApprovedKaizens(HeadingTitle,ListName,ElementToAppend){
//Get all current data from lists
var GetKaizenPromise = GetList( "Kaizen List",
"Id,Nominated_x0020_person, Status, Kaizen_x0020_Title,Division/Id, Team/Id,Division/Title, Team/Title, Name, Financial_x0020_Year, Kaizen_x0020_Category,Quarter",
"Division/Id, Team/Id,Division/Title, Team/Title",
"Status eq 'Approved'",
app);
$.when(GetKaizenPromise).done(function(KaizenSelectionData){
var EditButton = "";
var Results = KaizenSelectionData.d.results;
//Creates table structure and heading
var DataTableHtml = "";
var SetVotedBackground = "style='background-color:lightgreen;color:white;'";
var DivisionList = [];
var TeamList = [];
var YearList = [];
var DivisionCheck = [];
var TeamCheck = [];
if(Results.length > 0){
for(r=0;Results.length > r;r++){
TableCreated++;
var ResultsName = Results[r].Nominated_x0020_person;
var KaizenTitle = Results[r].Kaizen_x0020_Title;
var ResultsTeam = Results[r].Team.Title;
var ResultsDivision = Results[r].Division.Title;
var ResultsTeamId = Results[r].Team.Id;
var ResultsDivisionId = Results[r].Division.Id;
var ResultsCategory = Results[r].Kaizen_x0020_Category;
var ResultsStatus = Results[r].Status;
var ResultsQuarter = Results[r].Quarter;
var ResultsYear = Results[r].Financial_x0020_Year;
EditButton = "<p style='cursor:pointer;' class='edititem text-light-blue' data-itemid='"+Results[r].Id+"' data-listname='"+ListName+"'><i class='fa fa-edit'></i> View</p>";
DataTableHtml += "<tr>"+
"<td>"+ResultsName+"</td><td>"+ResultsDivision+"</td><td>"+ResultsTeam +"</td>"+
"<td>"+ResultsYear+"</td><td>"+ResultsQuarter+"</td><td>"+KaizenTitle +"</td>"+
"<td>"+ResultsCategory +"</td><td>"+EditButton+"</td>"
"</tr>";
//Create the drop down box info from all the results
if($.inArray(ResultsDivision , DivisionCheck ) == -1){
// Add to departments list
DivisionList.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
DivisionCheck.push(ResultsDivision);
//Keep duplicate of original divisions list
GlobalDivisionsArr.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
}
if($.inArray(ResultsTeam , TeamCheck) == -1){
// Add to Teams list
TeamList .push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
TeamCheck.push(ResultsTeam);
//Keep duplicates of original list
teamsArr.push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
}
if($.inArray(ResultsYear , YearList) == -1){
// Add to Year list
YearList.push(ResultsYear );
}
//next Item
}
}else{
//if there are no results
DataTableHtml = "<tr>"+
"<td colspan='8'>No results found</td>" +
"</tr>";
}
YearList.sort();
YearList.reverse();
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
popDD("kznSearchYear",YearList);
popDDSearchWithDataAttr("kznSearchTeam",TeamList,TeamList);
DivisionList.unshift({"FullName": "All","ID":"All"}); //Add All option to division list
popDDVal("kznSearchDivision",DivisionList);
//adds items to DOM
$(ElementToAppend + " tbody").html(DataTableHtml);
//Create column match with returned results
if (Results.length>0){
$.fn.dataTable.ext.errMode = 'console';
$(ElementToAppend).DataTable({
"dom": 'ftipr',
"responsive": true
});
}
$("body").css("overflow","");
//removes overlayer and loading symbol
$("#OverlayFade").addClass("hidden");
$("#Timer").addClass("hidden");
});
}
This snip of the script has popDDVal, and it looks like 'DivisionList' 'TeamList' 'YearList' is returning null. Since this is null it can not break from the loading overlayer.
I was able to narrow it down to this part.
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
Changed it to this, and it worked. But obviously the sorting is not sorted correctly, but least it works now...
TeamList.sort();
DivisionList.sort();
Instead of passing in an anonymous function pass the function name:
TeamList.sort(compareStrings);
or
DivisionList.sort(compareStrings);
I want to bring the json data to front end like in the picture.
How do i do it, here is my code. I want it nested like in the pic below.
This is how far i got with my code.
HTML:
</body>
<div id="active"></div>
</body>
JQuery
<script>
$.getJSON("active.json", function(result){
$.each(result, function(i, field){
var UniqueNames= $.unique(result.map(function (d) {
return d.gpanel;
}));
$("#active").append('<li>'+UniqueNames[i]+'</li>');
});
});
</script>
JSON:
[{"ID":"1","gpanel":"sfd","ptitle":"sdffd","panel":"1,2",
"free":"yes","fees":"0.00"},
{"ID":"2","gpanel":"sdfd","ptitle":"sdfds","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"3","gpanel":"sdf","ptitle":"sdf","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"4","gpanel":"sfd","ptitle":"fes","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"5","gpanel":"bbbfff","ptitle":"hgffg","panel":"1,2",
"free":"yes","fees":"0.00"}
]
thanks in advance.
Solution 1
You can try this code
$.getJSON("active.json", function(result){
var UniqueNames= $.unique(result.map(function (d) {
return d.gpanel;
}));
var ul_block = $("<ul/>");
$.each(UniqueNames, function(i) {
$(ul_block).append('<li>' + UniqueNames[i] + '</li>');
});
$("#active").append(ul_block);
});
I have made some changes in your code,
1) code which is used for fetching uniquenames was removed inside from loop, so that it will not process everytime even though you required once
2) changed the loop from result to UniqueNames, since you are displaying those names only
You can made changes in my code to get required output i.e level of display
Solution 2:
As per the data structure and conditions you provided, Please check this code
$.getJSON("active.json", function(result) {
var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance"];
var ul_block = $("<ul/>");
$.each(result, function(i, data) {
console.log(data);
var panels = data.panel.split(",");
var uli_block = $("<ul/>");
$.each(panels, function(j, jdata){
var ulii_block = $("<ul/>");
$(ulii_block).append($("<li/>").text(data.ptitle));
$(uli_block).append($("<li/>").text(panel_arr[panels[j]])).append(ulii_block);
});
$(ul_block).append($("<li/>").text(data.gpanel).append(uli_block));
});
$("#active").append(ul_block);
});
I have one Button that duplicates this line to choose more products.
My Html:
<td>
<input type="hidden" class="cod_linha" name="cod_linha[]"style="width: 100%;" />
<input type="text" name="linha[]" class="linha" style="width: 100%;" />
</td>
The problem is, I have two functions that find the product and other that Fill all the fields that I want automatically, what I have to do to differ this filled field of the empty field ? I tried this:
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== ''){
Executes my function to fill the fields and to add a new line.
}
else{ }
And this too :
var counter = $(table).find("input.linha").length;
for(var i =0; i < counter; i++){
if($(table).find('input.linha').eq(i).val()== ''{}
But those codes don't fill the other empty line. see the imagem :
My code to fill the fields :
function preencherCamposProduto(obj) {
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== '' &&
$(this).find('input.ref').val()=== '' &&
$(this).find('input.material').val()=== '' &&
$(this).find('input.cor').val()=== '' &&
$(this).find('input.descricao_marca').val()=== ''){
$.ajax({type: "POST",
url: '/pedidoOnline/index.php/Pedidos/pesquisarCamposProduto',
async: false,
data: {
cd_cpl_tamanho: obj
},
dataType: 'json',
success: function(data) {
var linhaId = data[0].idLinha;
var linhaLabel = data[0].labelLinha;
var refId = data[0].idRef;
var refLabel = data[0].labelRef;
var corId = data[0].idCor;
var corLabel = data[0].labelCor;
var marcaId = data[0].idMarca;
var marcaLabel = data[0].labelMarca;
var materialId = data[0].idMaterial;
var materialLabel = data[0].labelMaterial;`
var table = $('#tabelaPedido');
$(table).each(function() {
$(this).find('input.cod_linha').val(linhaId);
$(this).find('input.linha').val(linhaLabel);
$(this).find('input.cod_ref').val(refId);
$(this).find('input.ref').val(refLabel);
$(this).find('input.cod_material').val(materialId);
$(this).find('input.material').val(materialLabel);
$(this).find('input.cod_cor').val(corId);
$(this).find('input.cor').val(corLabel);
$(this).find('input.id_marca').val(marcaId);
$(this).find('input.descricao_marca').val(marcaLabel);
});
}
});
chamaAdicionarCampo();
}else{
console.log('Entrei no else');
}
});
}
Thanks a lot.
I've read your code and wrote a sample code in jsfiddle, that does things that you are writing about. In my solution I use CSS selector #tabelaPedido tr:last to select the last added row, and then write values to fields in this row.
Hope this helps.
The following simple jquery solution may help you:
$(document).ready(function(){
$('.linha').each(function(){
if ($(this).val() == ''){
//Call Your fill input function $(this) as parameter
}
});
});
Checkout This DEMO
With the answer of #zegoline and #semsem I figure it out.. Now it's working ! I added $( "tr:last" ).find() to every field on my each function and the #table tr:last too... Thanks a lot !