Use Data in JavaScript - 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>

Related

Unable to get this.value in this code

function showData(){
Object.keys(JSONcall).forEach(function(key){
var tvShow = JSONcall[key].show;
$('#show-select').append("<option class=\"selectS\"" +
"id=\"" + key + "\"" + "value=\"JSONcall[" + key + "]
.show\" onchange=\"selectShow(this.id)\">" + tvShow.name + "</option>");
});
}
Hello, I have this forEach loop where the function is to append the results of a JSON object. After appending the result is:
<option class="selectS" id="0" value="JSONcall[0].show"
onchange="selectShow(this.id)">Some Value</option>
First question: Is it wise to append onchange=(function()) like that?
selectShow(value) is a function meant to get id of <option> and display the data in another <div>.
Last question is why am I unable to get the results of this.id in this context?
create option element like this , and three is no need of id at option element as you are having val on option to identify it.
$('<option>').val(key).text(tvShow.name).appendTo('#show-select');
one more thing selectShow() must need to apply at to select not to option.
<select onchange= "selectShow()"> </select>
function selectShow(){
console.log($( "#show-select" ).val());
}
You have to put your onchange trigger on your select. I advice you to add event with javascript no in html attribute. You have to use value instead of id for sharing value.
const obj = {
channel1: {
show: {
id: "#ch1",
name: "ch1"
}
},
channel2: {
show: {
id: "#ch2",
name: "ch2"
}
}
};
function showData() {
$.each(obj, function(key, value) {
const tvShow = value.show; // obj[key] === value
$("<option></option")
.addClass("selectS")
.val(key)
.text(tvShow.name)
.appendTo("#show-select");
});
}
function selectShow() {
console.log($(this).val());
}
showData();
$("#show-select").on("change", selectShow)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="show-select"></select>
I have reworked your code in a different way.
Used $.ajax() to pull some random JSON data and parse it.
Used $.each(var, function(index, value) {}) to iterate over the object.
Used change() event to log text, val, id
The rest you can modify inside append() method.
function showData() {
$.ajax({
url: "https://www.json-generator.com/api/json/get/bHepFCoNmG?indent=2",
success: function(data) {
$.each(data, (i, val) => {
$("#mySelect").append('<option class="selectS" id="' + i + '" value="' + val.name + '">' + val.name + '</option>');
});
}
});
}
// change event
$('#mySelect').change(function() {
console.log($(this).find(':selected').text());
console.log($(this).find(':selected').val());
console.log($(this).find(':selected').attr("id"));
});
showData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id="mySelect">
</select>
</div>
The code below shows how to use jQuery.data() to solve the same issue:
//TODO: Add triggers and events
function showData() {
// Retrieve JSON file from website
$.ajax({
// Returns 15 rows
url: "https://www.json-generator.com/api/json/get/cuScfPsQRK?indent=2",
success: function(data) {
// Iterate retrieved JSON Object
$.each(data, (i, val) => {
// Get JSON keys
let key = val.key;
let value = val.value;
// Define metadata object
let metaData = JSON.stringify({
index : i,
key : key,
value : value
})
// Create template & pass configuration object
$('<option></option>', {
id : i,
text : key,
value : value,
class : "selectS",
'data-meta' : metaData
}).appendTo('#mySelect');
});
}
});
}
$('#mySelect').change(function() {
// Get data('meta') keys
let index = $(this).find(':selected').data('meta').index;
let key = $(this).find(':selected').data('meta').key;
let value = $(this).find(':selected').data('meta').value;
$("#dataId").text(index);
$("#dataKey").text(key);
$("#dataValue").text(value);
// Using template literals
//console.log(`================\nID: ${index}\nKey: ${key}\nValue: ${value}\n================`);
});
showData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Select a Person:</h3>
<hr>
<select id="mySelect">
</select>
<hr>
<div id="data">
Index:
<span id="dataId">N/A</span><br>
Key:
<span id="dataKey">N/A</span><br>
Value:
<span id="dataValue">N/A</span>
</div>

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.

Populate two select from JSON

This is my JSON file:
{
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
I need to populate two select boxes. The first one let choose between first level values (AL2,AN3,CME) and the second one between the deep level ones (AL2GR#,AN3GR#,CME).
My infile Javascript is :
var jsonData = {"AL2": {"3810": "AL2GR1","3814": "AL2GR2","3815": "AL2GR3"},"AN3": {"3818": "AN3GR1","3819": "AN3GR2"},"CME": {"2405": "CME"}};
$(window).load(function(){
$.each(jsonData,function(key, value) {
$('#ue').append('<option value=' + key + '>' + key + '</option>');
});
});
function grfromue(element,jsonData) {
var ue = $("#ue option:selected").text();
alert(ue);
$.each(jsonData[ue],function(key, value) {
$('#gr').append('<option value=' + key + '>' + value + '</option>');
});
};
And HTML :
<select id="ue" onChange="grfromue(this,jsonData);">
</select>
<select id="gr">
</select>
The second select box isn't changing, what am I doing wrong ?
Below snippet of code might be helpful to you
var json = {
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
};
to get each value in first level
$.each( json, function( key, value ) {
console.log( key );
});
to get second level values based on your first input
input = 'AL2';
$.each( json[input], function( key, value ) {
console.log( key + ' : ' + value );
});
Hope this helps you.
You can use a nested JQuery each method to iterate over the objects and the nested objects within them. You can extend it for as many nested objects as you like.
jQuery.each(obj, function(i, val) {
console.log("Object: " + i);
jQuery.each(val, function(j, value) {
console.log('It has ' + j + ' with value ' + value);
});
});
If you want to populate the second select box based on the value of the first, you can use array notation to fetch contents of the object. Something like this:
jQuery("#selec-id").change(function(){
$("#second-select-id").html("");
jQuery.each(obj[$(this).val()], function(key, value) {
$("#second-select-id").append("<option value='"+key+"'>"+value+"</option>");
});
});

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.

call an element inside json object with jquery

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']

Categories

Resources