Change portion of URL to show different data in JavaScript - javascript

JSFiddle Code
In this code, I parse data from a JSON url into a table.
When a certain portion of the URL becomes altered, different search results come out. So I'm trying to give the user an option to input a different keyword that will bring different results.
In python I would use a f string request, is there a similar option in JavaScript?
Python example:
device_name = simpledialog.askstring(title="510K Database",
prompt="Enter Keyword:")
r = requests.get(f'https://api.fda.gov/device/510k.json?search=device_name:{device_name}&limit=1000')`
My JavaScript code
$(document).ready( function () {
var table = $('#example').DataTable({
ajax: {
url: 'https://api.fda.gov/device/510k.json?search=device_name:glucose&limit=1000',
dataSrc: 'results',
cache: true,
},
many thanks

You would prompt and then use that variable as a template literal in your URL
$(document).ready(function() {
$('#echo').click(function() {
$('.error').empty();
let keyword = $('#keyword').val().trim();
if (!keyword) return $(this).prev('.error').html("Please enter a keyword first");
console.log(`The keyword is ${keyword}`);
/* let table = $('#example').DataTable({
ajax: {
url: `https://api.fda.gov/device/510k.json?search=device_name:${keyword}&limit=1000`,
dataSrc: 'results',
cache: true,
},
// ....
})
*/
})
})
.error {
color: #f00;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>510k Database // Enter Keyword
<input id="keyword" />
</label>
<div class='error'></div>
<button id='echo'>Click me</button>

Related

mdb_autocomplete drop down does not close on click event

In certain cases, usually after values have been cached from an initial search, I cannot get the mdb_autocomplete drop down to close on a single click. I often have to double click on my selection to get it to close. I am dynamically populating the values in the drop down via an Ajax call to a service method via and controller action method that searches the active directory for the first 30 name values. No call back occurs until a user enters at least 3 values into the mdb_autocomplete selection box. The callback and population of the drop down is working very well, but the click event following the selection of a value often will not close the dropdown. Additionally, we are being forced to use mdb boostrap over the normal bootstrap library. I have included the view, service, and typescript code that is being used to generate and populate the drop down.
View:
<div class="form-group">
<label class="font-weight-bold" for="RequestorSearchInput">Requestor</label>
<input type="text" id="RequestorSearchInput" name="RequestorSearchInput" class="form-control mdb-autocomplete" />
<span id="loading_data_icon"></span>
</div>
Service Method:
public List<string> GetRequestor(string aRequestor)
{
IEnumerable<Dictionary<string, string>> requestorNames;
using (ActiveDirectoryService service = new ActiveDirectoryService(<LDAP Domain Name>))
{
string[] propertiesToLoad = new string[] { "displayName" };
//requestorNames = service.SearchByPartialUsername(aRequestor, propertiesToLoad).Take(30).Union(service.SearchBySurname(aRequestor, propertiesToLoad).Take(30));
requestorNames = service.SearchBySurname(aRequestor, propertiesToLoad).Take(30);
}
return requestorNames.SelectMany(x => x.Values).Where(y => y.IndexOf(",", StringComparison.Ordinal) >= 0).Distinct().ToList();
}
TypeScript:
private handleRequestorSearch() {
let options: string[] = new Array();
// #ts-ignore
let searchval = $("#RequestorSearchInput").val().length;
if (searchval >= 3) {
$.ajax({
url: main.getControllerHREF("GetRequestor", "Search"),
method: "POST",
data: {
requestor: $("#RequestorSearchInput").val()
},
async: false,
dataType: "json",
success: function (names) {
$.each(names, function () {
options.push(this);
});
// #ts-ignore
$("#RequestorSearchInput").mdb_autocomplete({
data: options
}).select(function () {
$("#RequestorSearchInput").focus;
});
}
});
}
}

how to display array values in webpage from knockout js array

How will i be able to display the array values of FileList using foreach inside a div? and reiterate the items one by one?
dataservice code:
var GetUploads = function (GetUploadsObservable) {
var Importoptions = {
url: 'api/test/GetUploads',
type: 'GET',
async: true,
contentType: false,
processData: false,
};
return $.ajax(Importoptions).then(GetDataSucceded).fail(queryFailed);
function GetDataSucceded(data) {
var Filelist = [];
if (data != null) {
data.forEach(function (item) {
Filelist.push(new model.FolderFiles(item));
});
}
GetUploadsObservable(Filelist);
//alert("YYYY");
console.log(Filelist);
}
}
HTML code:
<div id="timesheet" class="" data-bind="foreach: Filelist" style="border:solid 1px red;">
</div>
Your question is bit vague, but if I'm understanding you correctly you're trying to loop through a list of files which you get from some kind of service.
Your file list variable is a local function array therefore isn't available to be bound to the view. What you might want to try is to bind to 'GetUploadsObservable' instead, and make sure GetUploadsObservable is part of your view model. See example below:
<div id="timesheet" class="" data-bind="foreach: GetUploadsObservable" style="border:solid 1px red;"><span data-bind="text: $data"></span></div>
Please see this link for more info on $data: http://knockoutjs.com/documentation/binding-context.html

Select File. Submit. Cannot select file again

I have a form with different fields and with input type="file". I use fileupload jQuery library.
Select file
Call
$('#some_id').fileupload().fileupload(
'send',
{
files: file,
url: widget.options.saveVideoUrl,
}
).success(
//...
(first fileupload called for init)
Try again to select file. Got: No files selected, clear console, etc..
Upd.1
The problem appear in E-commerce framework Magento2 in admin area.
The described form appear in such entity like 'slide-out panel'. It means that there is div block and this block wrapped in aside block using javascript.
<button onclick="jQuery('#new').modal('openModal')" .... >
<span>New</span>
</button>
Here is demo example:
Admin URL: https://iwdagency.com/magento2/admin
Username: admin
Password: admin123
Open Products / Catalog / select any product / click on New category
You should see following panel:
On such panel I've added by php constructor fields:
<div class="admin__field field field-new_video_screenshot " data-ui-id="product-tabs-tab-google-experiment-fieldset-element-form-field-new-video-screenshot">
<label class="label admin__field-label" for="..." data-ui-id="product-tabs-tab-google-experiment-fieldset-element-file-image-label"><span>Preview Image</span></label>
<div class="admin__field-control control">
<input id="...." name="image" data-ui-id="product-tabs-tab-google-experiment-fieldset-element-file-image" value="" title="Preview Image" type="file">
</div>
</div>
Script:
define([
'jquery',
'jquery/ui',
'Magento_Ui/js/modal/modal',
'mage/translate',
'mage/backend/tree-suggest',
'mage/backend/validation'
], function ($) {
'use strict';
$.widget('mage.newDialog', {
_create: function () {
var widget = this;
var newVideoForm = $('#new');
this.element.modal({
type: 'slide',
modalClass: 'mage-new-dialog form-inline',
title: $.mage.__('Create'),
buttons: [{
text: $.mage.__('Create'),
class: 'action-primary',
click: function (e) {
var file = $('#new_screenshot').get(0).files[0];
var result = $('#new_screenshot').fileupload().fileupload(
'send',
{
files: file,
url: widget.options.saveUrl,
}
).success(
function(result, textStatus, jqXHR)
{
var data = JSON.parse(result);
data['url'] = $('#new_url').val();
data['name'] = $('#new_name').val();
data['description'] = $('#new_description').val();
$('#media_gallery_content').trigger('addItem', data);
$('#new').modal('closeModal')
}
);
}
}],
});
}
});
return $.mage.newDialog;
});
I found the problem.
In my case the problem appear after initialization fileUpload library.
When I selected input:file, the library wasn't initialized (read as infected). When I pressed the button, initialization ran and any operations with this input become unavailable.
Solution is following: clone our input before it become infected, than do our operations and at the end replace existing infected input with its healthy copy, created before.

Liferay Alloy UI - Clearing cache of dependent AutoCompleteList

I need to have two dependent AutoCompleteList in my Liferay portlet page. When I select some value from first AutoCompleteList then based on it's selected value I need to change the second AutoCompleteList source data. Based on information available, I have done coding and it is working fine except one issue.
When I select item in first AutoCompleteList then second AutoCompleteList gets populated with certain values based on my first list's selected item. Then if I change my selection again in first list, second AutoCompleteList gets updated with new possible values. But it appends the new possible values in the existing list or can say keep caching of data from both cases. But I need to show only possible values in list based on current selection of first list. For example, for selected value 1 in first list, if initially it was showing [A, B] in second list, after changing selection in first list from 1 to 2, it is showing [[A,B]+[C,D]].
Below here is part of that code. I tried setting "enableCache: 'false' " in second AutoComepleteList but not working.
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',
function (A)
{
A.io.request('<%=getUrl %>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />name',
resultTextLocator: 'name',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
source:this.get('responseData'),
on: {
select: function(event) {
var result = event.result.raw;
A.one('#<portlet:namespace/>pk').val(result.id)
}
},
})
}}
});
});
</aui:script>
<aui:input id="pk" name="pk" label="Primary Id"
onChange='<%= renderResponse.getNamespace() + "fetchDisplayValues();"%
/>
Liferay.provide(
window,
'<portlet:namespace />fetchDisplayValues',
function() {
var A = AUI();
var pk = A.one("#<portlet:namespace/>pk");
var id = pk.get("value");
var url = '<%=getValues %>';
url = url+"&<portlet:namespace/>id="+id;
var datasource = new A.io.request(url,{
dataType: 'json',
method: 'GET',
on: {
success: function(){
var data = this.get('responseData');
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'false',
enableCache: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />displayName',
resultTextLocator: 'name',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
source:this.get('responseData'),
on: {
select: function(event) {
var result = event.result.raw;
A.one('#<portlet:namespace/>displayId').val(result.id);
}
},
})
}
}
});
})
</aui:script>
Please help me to resolve this issue. Thanks in advance.

Kendo template send data

What I want is simple but I don't know if it's possible.
I have a Kendo Mobile ListView as below:
e.view.element.find("#list-serviceorders").kendoMobileListView({
dataSource: ds,
pullToRefresh: true,
template: $("#list-serviceorders-template").html()
});
And I want to send to the template some values to access on it. My view with the template is this:
<div data-role="view" data-before-show="GAPCP.viewBeforeShow" id="serviceorders" data-layout="main-item-list">
<ul id="list-serviceorders"></ul>
</div>
<script id="list-serviceorders-template" type="text/x-kendo-template" data-teste="teste">
<a href="views/entries.html?id=#: CodOs #">OS: #: CodOs #<br />
#: parameter.Divi1 #: #: CodDivi1 #/#: parameter.Divi2 #: #: CodDivi2 #</a>
</script>
Where you can read parameter.Divi1 and parameter.Divi2 are the places where I want to display those values. They're are not in the Data Source like the others values.
I don't want to create global variable 'cause I don't want to mess with my code and I can't use a function for that purpose because those values come from the database and it will execute a query for each list item iteration.
Any suggestion of how do that?
What I'm proposing is adding this information to the model in the controller. You can do it in DataSource.schema.parse or in requestEnd, even in a dataBound event if the widget accepts it.
When the data is received you iterate through the model and fills the remaining data not received from the server.
Example: Using parse
var ds = new kendo.data.DataSource({
transport: {
read: {
url : ...
}
},
schema : {
model: {
CodOs : { type: "number" },
CodDivi1: { type: "string" },
CodDivi2: { type: "string" }
},
parse: function (data) {
$.each(data, function (idx, elem) {
// Extend original elem
elem.parameter = {
Divi1: elem.CodDivi1.toUpperCase(),
Divi2: elem.CodDivi2.toLowerCase()
}
});
return data;
}
}
});
Where I compute parameter inside the parse function and set parameter.Divi1 to CodDivi1 in upper-case and parameter.Divi2 to CodDivi2 in lowercase.

Categories