call an element inside json object with jquery - javascript

i am trying to call an element inside a json object, here is a part of the code
{
" academy": {
"business": {
"E-commerce": [
now i successed to call academy as the first element, by this code
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value) {
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key +
'</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
});
how can i get the "business" element now ?

Have you ever tried:
$.getJSON("professorUnversityCollegeCourseData.js", function(property) {
$.each(property, function (key, value){
$('#uni').add('<option value="'+ key + '" id="'+ count +'">'+ key + '</option>').appendTo('#university-selection');
arrayUni[count] = key;
count++;
alert(this.academy.business);//Or also this['academy']['business']
});
alert(property.academy.business);//Or also property['academy']['business']
});

I think what you should do is this:
$.getJSON("professorUnversityCollegeCourseData.js", function(property){
business = property.academy.business;
//-or-
business = property["academy"]["business"];
});
(according to the data you put up there.)

I assume this is what you are after
key.academy.business
It really is that simple, or :
key['academy']

Related

Use Data in JavaScript

I build this laravel query in my controller
public function getSpiel(){
$first = DB::table('Spielplan')
-> leftjoin('Verein', 'Spielplan.Heimmannschaft', '=', 'Verein.V_ID')
-> where('Spielplan_ID', '=', $spiel);
$final = DB::table('Spielplan')
-> leftjoin('Verein', 'Spielplan.Gastmannschaft', '=', 'Verein.V_ID')
-> where('Spielplan_ID', '=', $spiel)
-> union($first)
-> get();
return Responds($final);
}
The get() output of this query is like this [{"Spielplan_ID":1,"V_ID":7,"Name":"SV Werder Bremen","Liga":1},{"Spielplan_ID":1,"V_ID":1,"Name":"FC Bayern M\u00fcnchen","Liga":1}]
And now, I want to use it in my view in the java script part
$.get('/spiel?spieleID=' + spieleID, function(data){
$('#spiel').empty();
$.each(data, function(index, valueAusData){
$('#spiel').append('<option value="' + final.Heimmannschaft + '">'+final.Name+'</option>');
});
});
But what I have don't is not correct and I don't know to use this in my option part. Can anyone say how to use the values from collection in my option java script part?
Think is. This will work
$spiel = Input::get('spieleID');
$teamOutput = Spielplan::where('Spielplan_ID', '=', $spiel)->get();
return Response($teamOutput);
$('#spiel').append('<option value="' + valueAusData.Heimmannschaft + '">'+valueAusData.Heimmannschaft+'</option>');
This is exactly the same. And this one works and the other one not.
Something wrong in here
<div class="col-xs-2">
<label for="">Teamauswahl</label>
<select class="form-control input-sm" name="spiel" id="spiel">
</select>
</div>
Firstly, the logic inside your $.each is a bit off
$.get('/spiel?spieleID=' + spieleID, function (data) {
if (data.hasOwnProperty('final')) {
$('#spiel').empty();
$.each(data.final, function (index, valueAusData) {
$('#spiel').append('<option value="' + valueAusData.Heimmannschaft + '">' + valueAusData.Name + '</option>');
});
}
});
Secondly, change the return statement in your controller method from:
return Responds($final);
to
return compact('final');
Hope this helps!
You can get Name from value object
$.get('/spiel?spieleID=' + spieleID, function(data){
$('#spiel').empty();
$.each(data, function(index, value){
$('#spiel').append('<option value="' + value.V_ID + '">'+value.Name+'</option>');
});
});
Take a look at jquery document for more example http://api.jquery.com/jquery.each/
jQuery.each( array, callback )
array Type: Array The array to iterate over.
callback Type: Function( Integer indexInArray, Object value ) The
function that will be executed on every object.
Demo
var json = [{"Spielplan_ID":1,"V_ID":7,"Name":"SV Werder Bremen","Liga":1},{"Spielplan_ID":1,"V_ID":1,"Name":"FC Bayern M\u00fcnchen","Liga":1}];
$.each(json, function(index, value){
$('#spiel').append('<option value="' + value.V_ID + '">'+value.Name+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="spiel" id="spiel"></select>

Jquery loop once or show data once in array of data

I am using $.get() request to fetch data from Laravel controller and getting array of data in Javascript.
function getSpots1(){
var spots = $('#event-spots1');
spots.empty();
spots.html('<p><i class="uk-icon-refresh uk-icon-medium uk-icon-spin"></i></p>');
var event_id = $("#event-event_id").val();
var event_date = $("#event-date").val();
var code = '';
console.log(event_date);
$.get("/1/users/spots/" + event_id + "/" + event_date + "/date", function(data) {
spots.empty();
console.log(data);
code += '<label for="event_time" class="uk-form-label">Select Time</label><select class="uk-width-1-1" name="event_time" id="event-time">';
$.each(data.spots, function(index, value)
{
code += '<option value="' + value.event_time + '">' + value.event_time + '</option>';
});
code += '</select><p class="uk-form-help-block uk-text-muted">The spot you\'re booking</p>';
code += '</br><div class="uk-margin-bottom"><label for="event_time" class="uk-form-label">Price</label>';
$.each(data.spots, function(index, value)
{
code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />';
});
spots.append(code);
getSpots2();
});
}
I have $.each() jquery method to loop through array of Data. but for second $.each() method, I just need to loop once. I get value.price Multiple times depending on the loop length. For first $.each I need a loop because I have select input field.
Is there a another method instead of $.each to loop once through data variable? I am new and haven't really coded Jquery or Javascript before.
Well you could just get the first object in data.spots like for example data.spots[0].event_time and then you don't have to loop at all.
Less recommended, you could just put a return false; at the end of a loop like for example:
$.each(data.spots, function(index, value)
{
code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />';
return false;
});
which immediately stops the loop.

Is it possible to bind events during element concatenation in a loop?

Fiddle Example
The following is an example where several buttons are rendered via a loop. I was wondering if it is possible to bind events to each button as well during the loop before the buttons are appended to a container. My example doesn't work.
Jquery
function render(){
var input = '',
array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
input += '<h3>'+obj.title+'</h3>';
input += '<input type="submit" name="'+name+'" value="'+name+'"/>';
$(input).find('[name="'+name+'"]').click(function(){
alert(name)
/*** do some ajax things etc ***/
})
})
return input;
}
$('#box').append(render())
Yes but I wouldn't do it the way you are:
function render(target){
var array = [{'name':'Confirm','title':'This'},{'name':'Cancel','title':'That'}]
$.each(array,function(k,obj){
var name = obj.name;
var h3 = $('<h3/>').text(obj.title);
var input = $('<input/>')
.attr('type', 'submit')
.attr('name',name)
.val(name);
input.click(function() {alert('test');});
target.append(h3);
target.append(input);
})
}
$(document).ready(function(){
render($('#box'));
});
So create jquery objects that will be rendered, then attach the event to these objects. Then once the object is built ask jquery to render them.
This way jquery can keep track of the DOM elements, in your example your stringfying everything. Jquery hasn't built the DOM element at the point where your attempting to bind to them.
Fiddle
You need to use filter() to find the element by the name as there is no parent selector to find() within:
$(input).filter('[name="' + name + '"]').click(function(){
alert(this.name)
/*** do some ajax things etc ***/
})
No, you can't bind event handlers to strings. You will need to create HTML elements first. I would recommend to bind single delegated event handler after your HTML string is appended, it's also going to be much better in terms of performance:
function render() {
var input = '',
array = [{'name': 'Confirm','title': 'This'}, {'name': 'Cancel','title': 'That'}]
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
});
return input;
}
$('#box').append(render()).on('click', 'input[name]', function() {
alert(this.name);
/** do some ajax things etc **/
});
Demo: http://jsfiddle.net/KHeZY/200/
This can be done properly by using event-delegation, But since you concerned, I just written a solution by using .add() and .filter()
function render() {
var input = '',
array = [{
'name': 'Confirm',
'title': 'This'
}, {
'name': 'Cancel',
'title': 'That'
}],
elem = $();
$.each(array, function (k, obj) {
var name = obj.name;
input += '<h3>' + obj.title + '</h3>';
input += '<input type="submit" name="' + name + '" value="' + name + '"/>';
elem = elem.add($(input));
input = "";
});
elem.filter("[name]").click(function () {
alert(this.name);
})
return elem;
}
$('#box').append(render())
DEMO

How to get Json as key and value in the Ajax $.getJSON()?

I have this ajax code for getting json from Jobs.json file.
$(document).ready(function(){
$('#btn2').click( callJobs );
});
function callJobs()
{
alert("getting results...");
$.getJSON('Jobs.json', function(JSON){
$('#result').empty();
$.each(JSON.jobs, function(i, JOB){
$('#result')
.append(JOB.Job +'<br />')
.append(JOB.Priority+'<br />')
.append(JOB.DueDate+'<br />')
.append(JOB.Iscompleted+'<hr />');
});
});
}
Jobs.json code is below.
{
"jobs":[
{
"Job":"Job1",
"Priority":"Low",
"DueDate":"11.03.2013",
"Iscompleted":"No"
},
{
"Job":"Job2",
"Priority":"High",
"DueDate":"11.03.2013",
"Iscompleted" : "No"
},
{
"Job":"Job3",
"Priority":"Medium",
"DueDate":"11.03.2013",
"Iscompleted":"No"
}
]
}
Now I want to rewrite $.each function dynamically.That is, it will write the json string as key and value instead of .append() .
This would walk over the properties of each job dynamically:
$.getJSON('Jobs.json', function(JSON){
var $container = $('#result').empty();
$.each(JSON.jobs, function(i, JOB) {
$.each(JOB, function(key, value) {
$container.append(key + ': ' + value + '<br />');
});
$container.append('<hr />');
}
});
Demo
Here's my approach. I've added comments to explain the process.
$.each(JSON.jobs, function(i, JOB) {
// an empty array for the output values
var values = [];
// iterator over each property in the current JOB object
for (var prop in JOB) {
// add an item to the array in format "key: value"
values.push(prop + ': ' + JOB[prop]);
}
// join the array values using '<br />' as separator;
// append to #result and add an '<hr />' after
$('#result').append(values.join('<br />')).append('<hr />');
});
My goals for this solution were to keep it readable (at the cost of an added array), select the #result element only once, and not have to deal with knowing whether to add that last <br /> during each loop. The other solutions append an extra <br /> after the last property and before the <hr /> whereas this and your original solution do not.

Jquery reading input field that was created from JSON loop

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

Categories

Resources