I have a variable with jsonData in my page:
JSON_Values=[
{"ID":"1","Name":"MyName1","Selector":"S1"},
{"ID":"2","Name":"MyName2","Selector":"S2"}
]
The name JSON_Values can change so I have receive a variable that holds the name of the JSON_Values:
function useJSONData(nameOfVariable, filter) {
//How to access the Data inside of JSON_Values here???
//Value of nameOfVariable is correctly set to JSON_VALUES
var myJSONData = $(nameOfVariable);
jq.grep(myJSONData, function (n, i) {
return n.Selector === filter
});
}
Can someone provide me any help?
If nameOfVariable is in global scope (which you should avoid), you can use
window[nameOfVariable]
or if in object scope:
this[nameOfVariable]
You can accessing the json data like so: var id = myJSONData[0]["ID"]
You can loop through if you need to do something for each item.
Here's a little example: Hope its helpful.
function useJSONData(nameOfVariable, filter) {
//How to access the Data inside of JSON_Values here???
//Value of nameOfVariable is correctly set to JSON_VALUES
var myJSONData = $(nameOfVariable);
$.each( myJSONData, function( index, value ){
var id = myJSONData[index]["ID"]
var name = myJSONData[index]["Name"]
var selector = myJSONData[index]["Selector"]
var result = "<p>" + id + " | " + name + " | " + selector + "</p> <br>"
$("#output").append(result);
//value("<p>" + id + " | " + name + " | " + selector + "</p> <br />");
});
}
JSON_Values=[
{"ID":"1","Name":"MyName1","Selector":"S1"},
{"ID":"2","Name":"MyName2","Selector":"S2"}
]
useJSONData(JSON_Values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="output"></div>
Related
I have problem in for loop, as I am calling all the value from the attribute to options, but it has duplicate value so i used set and get function, with that I also want to call the values like district and plot no. but while doing so it returns the last value of attribute table data.
so, how can i get a values with selected feature only?
$(function () {
GetFeatures();
$('#selectds').change(function () {
console.log($(this).find(":selected").attr('tk'));
console.log($(this).find(":selected").attr('pt'));
});
function GetFeatures() {
var options = "";
let mySet = new Set();
$.each(farmdata.features, function (layer, dsdata) {
dsname = dsdata.properties;
console.log(dsname);
mySet.add(dsname.District);
});
//problem in for loop
for (const item of mySet.values()) {
options += "<option value='' tk='" + dsname['Taluka'] + "'pt='" + dsname['Name'] + "'>" + item + ',Gujarat' + "</option>"
}
$("#selectds").html(options);
console.log(options);
}
});
var number = 0;
$.getJSON("blogData.json", function(data) {
$.each(data, function (index, entry) {
console.log(index);
$("#posts").append("<h3>" + entry.title + "</h3>");
$("#posts").append("<h4>" + entry.desc + "</h4>");
$("#posts").append("<h4>" + entry.author + "</h4>");
$("#posts").append("<p>" + entry.post + "</p>");
$("#posts").append("<br>");
$("#posts").append('<button onclick=save(number)>Read More</button>');
$("#posts").append("<br><br>");
number++;
});
});
I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.
You have used the variable as string type. All what you need is to concatenate the variable's value.
$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');
The form is set up to take user input which is being collected into a the address var.
Using jQuery to serialize address per url requirements. jquery serialize
Using getJSON to send the request to google geocode api.
Using a for in loop within a for loop to run through the results.
Finally, accessing the JSON results.
Question: Why am I getting undefined as result?
Code:
$(function() {
var address = document.getElementById('address').value;
address += " "+document.getElementById('street_add').value;
address += " "+document.getElementById('city').value;
address += " "+document.getElementById('state').value;
address += " "+document.getElementById('postcode').value;
$('#clickme').click(function() {
var strAddress = $( "address" ).serialize();
// data is an object containing info also called a map key/values
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=strAddress&sensor=false", function( data ) {
for (var i = 0; i <= data.length; i++) {
for (key in data.results[i]) {
var mystring = data.results[0].formatted_address;
var mylat = data.results[0].geometry.location.lat;
var mylng = data.results[0].geometry.location.lng;
}
}
$("<ul/>", {
"class": "zombies",
html: document.write(mystring,'<hr />', mylat, '<hr />', mylng),
}).appendTo( "body" );
});
});
});
Firstly, you need to append the value of address to the url string.
Secondly, you are assigning the return value of document.write to the html property of the new ul element. document.write does not return anything, hence you are seeing undefined.
Also, you are looping through data.results but for every iteration only retrieve the first item hence the for is redundant. Try this instead.
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=" + strAddress + "&sensor=false", function( data ) {
var mystring = data.results[0].formatted_address;
var mylat = data.results[0].geometry.location.lat;
var mylng = data.results[0].geometry.location.lng;
$("<ul/>", {
"class": "zombies",
html: mystring + '<hr />' + mylat + '<hr />' + mylng),
}).appendTo("body");
});
I have a javascript function ...
function check_val(name, cat)
{
alert(cat);
var val = name.indexOf('[');
if (val == -1){
//$('input[type="checkbox"][value='+ name + ']')[0].click()
val = '"' + name + '"'
type = "'" + cat + "'"
$.get(url,{'ajaxtype':'content', type : val}, function(data{$('#search_container').html(data);$('#rotator').hide();});
}
}
when i call this function with argument say check_val('xyz','pqr')
The problem is when I check the request.get parameter I am getting
<QueryDict: {u'type': [u'"xyz"'], u'ajaxtype': [u'content']}>
instead of
<QueryDict: {u'pqr': [u'"xyz"'], u'ajaxtype': [u'content']}>
Build the object beforehand and use array subscript syntax:
var requestData = { 'ajaxtype': 'content' };
requestData[type] = val;
$.get(url, requestData,
function(data{$('#search_container').html(data);$('#rotator').hide();});
Instead of {'ajaxtype':'content', type : val} try {'ajaxtype':'content', "'" + cat + "'" : val}.
This way JS should know that it's not key name but variable.
My "stack" is totally overflow, so I need a help :)
I trying to get all values from FORM and save them to associative array. Here is a code:
var dat = [];
$('form[name=' + form.name + '] input[name], form[name=' + form.name + '] select[name], form[name=' + form.name + '] textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
I am waiting for all values become in dat after this piece of code, but it looks like dat is internal variable of .each() lambda function, so it is unavailable after .each() is completed.
How to return resulting dat[] from the cycle ?
Try this
function() getFormData(){
var dat = {};
$('form[name=' + form.name + ']').find('input[name], select[name], textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
return dat;
}
This function will return a json object containing all the form elements name/value pair specified in the selector.