I am using JQuery to autocomplete names from a remote database... this all works fine.
However, I want to also get ALL the information associated with that name from the autocomplete and save it to a php array...
Can anyone help?
This is my code for the autocomplete
<script type="text/javascript">
$(function() {
$("#findname").autocomplete({
source: "templates/search2.php?field=sire",
minLength: 5
});
});
</script>
And here is how I call it...
<input type="text" name="name" id = "findname" size="45"><br>
So, when I find the name I am looking for, which works fine, how can I return ALL the data for that named record and store to an array, to then call a modal with the data ?
Thanks
if i understand your question, you want to get the data of a worker to show in a modal, well, first you need to get all the data you want in a single call, not just the names, but also the mail, age or other atributes, then you save it in an object .
For example:
After you called the information, you should get something like this :
var workersData=[{name:"a1",mail:"m1",age:20},
{name:"a2",mail:"m2",age:20},
{name:"a3",mail:"m3",age:20},
{name:"a4",mail:"m4",age:20}];
Then you create a method to get all the names and put this array in the autocomplete input:
function listStringsFromArray(list, atribute) {
var arrayString = [];
if (list) {
for (var index = 0; index < list.length; index++) {
arrayString.push(list[index][atribute]);
}
}
return arrayString;
}
$("#findname").autocomplete({
source: listStringsFromArray(workersData,"name"),
minLength: 5
});
Finally add a method for the input, so anytime it changes, to search for the rest of the data in the workers array and put the information where you want:
$("#findname").keypress(function(e){
fillDataModalWorker(); });
function fillDataModalWorker(){
var workerName=$("#findname").val();
var mail,age;
for (var index = 0; index < workersData.length; index++) {
if(workersData[index]["name"]==workerName){
mail=workersData[index]["mail"];
age=workersData[index]["age"];
$("#inputMailModal").val(mail);
$("#inputAgeModal").val(age);
break;
}else{
$("#inputMailModal").val("Worker´s information not found");
$("#inputMailModal").val("Worker´s information not found");
}
}
}
Hope it hepls.
Related
I'm trying to build a search option where user will input their ID and they will see the result of that corresponding ID which is stored in google spreadsheet.
Like user will input:
1 and they will see result : Nitu
5 and they will see result : Dipon
<input id="id" type="text" placeholder="Your ID">
<input id="search" type="submit" value="Search">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function displayContent(json) {
var string = "<table>";
var len = json.feed.entry.length;
for (var i=0; i<len; i++) {
var id = json.feed.entry[i].gsx$id.$t;
var name = json.feed.entry[i].gsx$name.$t;
string += '<tr><td>' + id + '</td><td>' + name + '</td></tr>';
}
string += "</table>";
$(string).appendTo('body');
}
</script>
<script src="http://spreadsheets.google.com/feeds/list/1WMvFqepPmQUVwTFFUZW_3SfSt1ZBr_AEy_XdUXZ72ng/od6/public/values?alt=json-in-script&callback=displayContent" type="text/javascript"></script>
I can fetch data from my google sheet using the above code snippet. But I don't want to fetch all data at a time. I want only specific data based on search with ID.
So now how can I integrate this search feature in javascript?
You can use Structured Query for google spreadsheet API.
So if make a GET request with proper Structured Query and you will get the relevant data only. in your case add sq=id==5 as query parameter.
So rather then get the whole data onload and parse it afterwads, you should make a function which will make proper GET request and fetch you Only the data you need.
var fetchName = function(ID, workSheetID){
var url = 'https://spreadsheets.google.com/feeds/list/'+workSheetID+'/od6/public/values?sq=id='+ID+'&alt=json-in-script&callback=?';
$.get( url, function( data ) {
//Parse and Do Your Stuff Here
});
}
Plunker Sample
Hope this helps. Cheers !!
instead of doing a for loop just use filter to filter the corresponding ID. For exmaple:
function displayContent(json) {
var output = json.feed.entry.filter(function(name){
return name.gsx$id.$t === '2'
})
$('body').append(" <p>" + output[0].gsx$name.$t + "</p>");
Heres the edited version, just replace '2' with your id or with the input value getter and it should work. Notice you need to reference the output in array like syntax. fiddle
Cross reference your code with the answer provided carefully!
1) your filter: --> return element.gsx$id.$t === 2
The comparison may not return the expected result
--> return name.gsx$id.$t === '2'
2) The returned data if your comparison produces any result would be in the variable 'name'. var name is in an array. You are to use indexes to access the array elements. Therefore, taking that into account, you should change yout code to:
var test = name[0].gsx$id.$t;
Here you are correctly accessing the data returned.
3) Always make sure there is data to access. Your array must not be empty if you try to access it.
I'm trying to get the "formatted_address" value from this
JSON file. I'm new to this and found the documentation quite confusing. The code I have now is the following where the variable "location" is the url generated like the one above.
$.getJSON(location, function( data ){
stad = data.results.formatted_address;
console.log(stad);
});
How would I achieve this?
results is an array, so you need to access it as one. Given your example with only one item, you can access it directly by index:
var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"
If there were multiple items in the array you would need to loop through them:
for (var i = 0; i < data.results.length; i++) {
var stad = data.results[i].formatted_address;
// do something with the value for each iteration here...
}
$.each(data.results,function(key,value){
console.log(value.formatted_address); //'s-Hertogenbosch, Netherlands
});
I'm passing a List from my controller to a view, where I want to be able to take the Model and loop through results in JQuery/Javascript. I'm having a heck of a time figuring out how to do that.
My controller returns a list of colors. In the view, I converted the List to an array. I then pass it to my where I'm trying to loop through it to build an array I can using in my JS.
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr;
for (i=0; i<#arr.Length; i++) {
jsArr.push(#arr[i])
}
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#arr[0].Location')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
There has to be an easy way of doing this...
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr = #Html.Raw(Json.Encode(arr)) ;
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#Html.Raw(arr[0].Location)')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
I would instead return json from the server. However if you want to do it in an html view I think something like this might work:
var jsonObj = '#Html.Raw(Json.Encode(Model.arr))'
//the loop is unnecessary, but can be useful if you need additional processing
var myArray = [];
for (i=0; i<jsonObj.length; i++) {
myArray.push(jsonObj[i])
}
Here is a way to manually build a JSON or JS object with razor code, some very easy to use code:
#foreach (var item in Model.Users)
{
<text>
UserData[UserData.length] = {
"UserID": '#item.ID', "FullName": '#item.Name'
};
</text>
}
I purposefully showed model property names being used and JSON property names being different to show an advantage of manually building the array.
Also, in this case you would be able to send a model through with multiple collections of data. Then just iterate through that collection (#foreach (var item in Model.Users)) with your Razor code to build your JSON or Javascript object array
selected files preview with fileReader in javascript
if i remove from previewed image. it must delete from selected files!
$scope.getFile = function () {
$scope.progress = 0;
$scope.variant.images = [];
var files = $scope.file;
for ( var i = 0; i < files.length; i++) {
var file = files[i];
fileReader.readAsDataUrl(file, $scope).then(function(result) {
$scope.variant.images.push({path: result})
});
}
};
i try like this but it does not works
angular.forEach($scope.file, function (value, key) {
if(key === id){
delete value;
}
})
You cannot splice a FileList. It is readonly! It only has the length and item but no array logic like splice', 'split., etc. So you will have to make a copy from it in an array:
// **A**
$scope.fileArray = [];
angular.forEach($scope.file, function(file) {
$scope.fileArray.push(file)
});
And then you can splice from this array with something like:
$scope.deleteImage = function(index) {
$scope.fileArray.splice(index, 1);
})
As you mention 'preview' I guess you are displaying a thumbnail of the selected images. You will have to change any display logic also to use the fileArray instead of the current file. So it automatically updates when the user removes one element.
<div ng-repeat="image in fileArray"... >
So best to set up an angular watch to recalculate $scope.fileArray as given above. However I'm afraid you cannot do a $watch on a file list. Not certain, but I recently found out that Angular does NOT support ng-model on a <input type="file". I found a solution for this in this article.
So if a simple $scope.$watch('file', function.. doesn't work, you'd best import use the fileModel directive in that into your system and enhance the file-input in your view with it:
<input type="file" name="files" file-model="filesArray" multiple accept="image"/>
You should then be able to watch that filesArray you assign to it:
$scope.$watch('fileArray', function() {
// Code from **A**
....
});
You can use native JS Array#forEach function as it gives you access the index of the object in the array.
I used id assuming you are actually passing an id in to the function to identify the object that needs to be deleted from the array. Looking at your code above, name seems more ideal, if that's unique property in the object of course
$scope.file.forEach(function(file, index){
if (file.id === id){ // Where id is your identifier, could be file.name === name.
this.splice(index, 1);
}
});
I have a generic function for clear the text box and checked the radio button. The following are the code for that function
function initData(checkId,data) {
alert(checkId);
var i;
for (i = 0; i < data.length; i++) {
alert(data);
document.getElementById(data).value = "";
}
document.getElementById(checkId).checked = true;
alert('done');
}
Now I need to create an array in jsf tags using Onchange function.The following are the code
<h:inputText value="#{termPurchaseUIBean.effectiveRate}" styleClass="textInput" id="effectiveRateText" onchange="initData2('termPurchase:selectRate:1',new Array()['termPurchase:effectiveRateText']);" label="#{label.TermPurchase_EffectiveRate}">
`
But this code is not working. Can any one of you help me to create an array in this scenario.
The document.getElementById() call inside the loop is incorrect. You want to pass the current array item data[i] as ID, not the whole data array.
document.getElementById(data[i]).value = "";
The array creation is incorrect. Remove the new Array(). It will already implicitly be done with [].
onchange="initData2('termPurchase:selectRate:1', ['termPurchase:effectiveRateText']);"