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>
Related
I have a JSON array in a JSON file looks like this:
{
"states": [
{
"state": "Andhra Pradesh",
"districts": [
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Krishna",
"Kurnool",
"Nellore",
"Prakasam",
"Srikakulam",
"Visakhapatnam",
"Vizianagaram",
"West Godavari",
"YSR Kadapa"]
}
]
}
and I am successfully able to load all states in the select element as a dependent select option
. when I select a state from a select element it populates a related array in the district select element.
but instead of the array showing a separate option it shows as one option:
Should I modify my JSON array in a different format?
jquery
$('#statePicker').on('change', function() {
$("#cityPicker").html('');
$.ajax({
url: "{{ asset('json/in-sc-list.json') }}",
type: "GET",
dataType: 'json',
success: function(res) {
$('#cityPicker').html('<option value="">Select City</option>');
$.each(res.states, function(key, value) {
if (value.state == $('#statePicker').val()) {
console.log(value.districts);
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
});
}
});
});
blade
<span>
<select id="statePicker" name="statePicker" required class="form-control"></select>
<select id="cityPicker" name="cityPicker" required class="form-control"></select>
</span>
Your data structure is fine. The issue is that you're not creating multiple option elements, you're only creating one. This part is off:
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
What you want to do is create an option element for each district, as follows:
for (const district of value.districts) {
$("#cityPicker").append('<option value="' + district + '">' + district + '</option>');
}
let statePicker = $('#statePicker').val();
let list = $("#cityPicker");
$.each(res.states, function(key, value) {
if (value.state == statePicker) {
$.each(items, function(item) {
list.append(new Option(item, item));
});
}
});
You need to loop value.districts because its an array, and also, you are doing it in a dirty way, you are initializing $("#cityPicker") on every loop, This might give some performance issues in future if the list items increases.
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>
hopefully somebody can help me. The JS below, loads a JSON file and parses the counties into a select menu. It also removes duplicates. Now in the JSON feed, each item has something like this:
{
"County":"Antrim",
"Town":"Antrim Town",
"Restaurant":"Diane's Restaurant & Pizzeria"
}
What I am trying to do is in the first select menu, once the user chooses the county, the second select menu is updated with values from the son object. At the moment I'm getting a 'Cannot find variable' error and I can't work out why. Is the data array not available for some reason?
<script type="text/JavaScript">
$(document).ready(function(){
//get a reference to the select elements
var county = $('#county');
var town = $('#town');
var restaurant = $('#restaurant');
//request the JSON data and parse into the select element
$.getJSON('rai.json', function(data){
console.log(data);
//clear the current content of the select
$('#county').html('');
$('#county').append('<option>Please select county</option>');
$('#county').html('');
$('#town').append('<option>Please select town</option>');
$('#restaurant').html('');
$('#restaurant').append('<option>Please select restaurant</option>');
//iterate over the data and append a select option
$.each(data.irishtowns, function(key, val) {
county.append('<option id="' + val.County + '">' + val.County+ '</option>');
});
var a = new Array();
$('#county').children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
});
$( "#county" ).change(function() {
var myCounty = $(this).val();
console.log(myCounty);
$.each(data.irishtowns, function(key, val) {
if (val.Town === myCounty) {
town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
}
});
});
});
</script>
Data is not in scope in this line
$.each(data.irishtowns, function(key, val) {
You could move this up into the callback, or use a global variable to provide access: i.e. in the callback have a line countries = data and then
$.each(countries.irishtowns, function(key, val) {
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>");
});
});
Say I have a ListBox populated with a name value pair SelectList(myUsers, "Key", "Value"):
#Html.ListBox("ListReviewers", (SelectList)ViewBag.ListOFReviewers, new { style = "width:120px;" })
I want to double click an option in this ListBox, and place it in a SelectionList like below:
<div class="selectedEmployees">
<select class="selectionList" multiple="multiple" name="AssignedReviewer" style="width:120px;">
<!--x.UserID, x.FirstName + " " + x.LastName) -->
<option value=""></option>
</select>
</div>
Once this collection is placed in the above, I want to store all the values in another SelectionList Collection for later use.
Here is the start of my jQuery code:
<script type="text/javascript">
$('#ListReviewers').dblclick(function (i, selected) {
//double click on this value of listbox of type SelectList(myUsers, "Key", "Value")
//store this value and text
var value = $(this).val;
//var empName = $(this).data[0];
var empName = $(selected).text();
alert(empName);
//append an option element <option value=""></option>
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
I can get the value of the dblclicked collection object, but not the text of the collection object. Is there a better way to do this?
Try attaching your event to the option within the select itself. You can then use this to access it's properties.
$('#ListReviewers option').dblclick(function () {
var value = $(this).val();
var empName = $(this).text();
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
Alternatively, you can use clone() and append() to move the option from one select to the other. This will save you having to worry about duplicate options being appended.
$('#ListReviewers option').dblclick(function () {
var $newOptions = $(this).clone(false);
$(this).remove();
$('.selectionList').append($newOption);
});