Add JSON to option values - javascript

I've been working with PHP for a while. I just started learning how to work with JSON.
I was able to create a PHP file that returns JSON. In my main file, I reference the PHP file and get the JSON objects.
I can display the objects in a dropdown select menu like this:
$.getJSON( "folder/services.php", function( data )
{
$.each(data, function(index, item)
{
$('#service').append($("<option>" + item.SERVICE + "</option>"));
});
});
The above code works fine. I can display the SERVICE values in the dropdown SELECT options.
What I am trying to figure out is how to get the SERVICE into the VALUE of the OPTION. I hope I am saying that correctly.
Typically, the OPTION tag would look like this:
<option value="SERVICE_A">Service A</option>
<option value="SERVICE_B">Service B</option>
...
But since I'm using JSON, I am not sure how to get the value into the OPTION.
I attempted to use PHP inside of the JQuery, but was unsuccessful. I'll show you what I attempted:
$('#service').append($("<option value='".+ item.SERVICE +."'>" + item.SERVICE + "</option>"));
****** EDIT ******
I attempted this piece of code submitted by LShetty below:
$.getJSON( "folder/services.php", function( data )
{
var strToAppend = "";
$.each(data, function(index, item)
{
strToAppend += $("<option/>",
{
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
});
I only came up blank with this code. Does anyone see what I did wrong?

You're on the right track. Don't try to use . for concatentation in JS, though; it's a PHP thing. And .+ doesn't work in either language.
A safer, more jQuery-ish way to do this (it will work when ", ', <, etc. are present in the SERVICE value):
$('<option>').
attr('value', item.SERVICE).
text(item.SERVICE).
appendTo($('#service'));

Paul has the answer above. This is more of an optimization take. Modifying DOM in a loop is costly! it may be okay in this specific question as I only see 2 items. Hence, always construct your string outside of the loop and append all at once when you are ready.
var strToAppend = "";
$.each(data, function(index, item) {
strToAppend += $("<option/>", {
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
Hope that helps :)

Related

Getting certain items with get

Sorry if my title is a little confusing I don't know really how to explain it.
API: http://mcping.net/api/162.223.8.210:25567
So I have this code that goes to an API, and I only want it to get the 'variables' online, and max. How would I do this?
Code:
$.get('http://mcping.net/api/162.223.8.210:25567', function(data){
$.each(data, function(index, item){
console.log(index + " ; " + item)
});
});
Try this
$.get('http://mcping.net/api/162.223.8.210:25567', function(data){
console.log(data.online);
console.log(data.max);
});
If your data is already a Javascript object, so you can call its variables properties like in the snippet code.
Just in case I tested it in this fiddle http://jsfiddle.net/js18ykj1/

Clear dropdown using jQuery Select2

I'm trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 query option.
HTML:
<input id="remote" type="hidden" data-placeholder="Choose Something" />
Javascript:
var $remote = $('#remote');
$remote.select2({
allowClear: true,
minimumInputLength: 2,
query: function(options){
$.ajax({
dataType: 'json',
url: myURL + options.term,
error: function(jqXHR, textStatus, errorThrown){
smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
},
success: function(data, textStatus, jqXHR){
var results = [];
for(var i = 0; i < data.length; ++i){
results.push({id: data[i].id, text: data[i].name});
}
options.callback({results: results, more: false});
}
});
}
});
Unfortunately, the call to $remove.select2('val', '') throws the following exception:
Uncaught Error: cannot call val() if initSelection() is not defined
I've tried setting the attr, setting the val, text and the Select2 specific data function. Can't seem to make the guy clear and work in a radio button like manner. Anyone got suggestions?
This works for me:
$remote.select2('data', {id: null, text: null})
It also works with jQuery validate when you clear it that way.
--
edit 2013-04-09
At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.
$remote.select2('data', null)
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
This is the proper one, select2 will clear the selected value and show the placeholder back .
$remote.select2('data', null)
For select2 version 4 easily use this:
$('#remote').empty();
After populating select element with ajax call, you may need this line of code in the success section to update the content:
success: function(data, textStatus, jqXHR){
$('#remote').change();
}
Using select2 version 4 you can use this short notation:
$('#remote').html('').select2({data: {id:null, text: null}});
This passes a json array with null id and text to the select2 on creation but first, with .html('') empties the previously stored results.
You should use this one :
$('#remote').val(null).trigger("change");
Method proposed #Lelio Faieta is working for me, but because i use bootstrap theme, it remove all bootstrap settings for select2. So I used following code:
$("#remote option").remove();
I'm a little late, but this is what's working in the last version (4.0.3):
$('#select_id').val('').trigger('change');
This solved my problem in version 3.5.2.
$remote.empty().append(new Option()).trigger('change');
According to this issue you need an empty option inside select tag for the placeholder to show up.
These both work for me to clear the dropdown:
.select2('data', null)
.select2('val', null)
But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3
I found the answer (compliments to user780178) I was looking for in this other question:
Reset select2 value and show placeholdler
$("#customers_select").select2("val", "");
From >4.0 in order to really clean the select2 you need to do the following:
$remote.select2.val('');
$remote.select2.html('');
selectedValues = []; // if you have some variable where you store the values
$remote.select2.trigger("change");
Please note that we select the select2 based on the initial question. In your case most probably you will select the select2 in a different way.
Hope it helps.
For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.
this code remove all results for showing new list if you need:
$('#select2Elem').data('select2').$results.children().remove()
For example, in the list of provinces and cities, when the province changes and we click on the city input, the list of old cities is still displayed until the new list is loaded.
With the code I wrote, you can delete the old list before calling ajax
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items
$('#mySelect2').val(null).trigger('change');
This is how I do:
$('#my_input').select2('destroy').val('').select2();

JavaScript variable carry an ID that I need to use in a Html.ActionLink

I have a JavaScript variable in my jQuery code that contains an ID that I need to use in my Html.ActionLink but it's not working:
#(Html.ActionLink("Genomför", "AnswerForm", "AnswerNKI", new {id = goalcard.Id},null))
I get: 'cannot resolve symbol "goalcard"', and the reason is that goalcard is a JavaScript variable.
This is what it looks like:
$.post('#Url.Action("Search", "SearchNKI")', data, function (result) {
$("#GoalcardSearchResult tbody").empty();
result.forEach(function(goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
// steg Create a row for each result
html: "<td>" + goalcard.Name +
"</td><td>" + goalcard.Customer +
"</td><td>" + goalcard.PlannedDate +
"</td><td>" + goalcard.CompletedDate +
"</td><td>" + '#(Html.ActionLink("Genomför", "AnswerForm", "AnswerNKI", new {id = goalcard.Id},null))' + "</td>"
}));
});
});
I have been testing for while now and I almost found a solution and it looks like this:
#(Html.ActionLink("Genomför", "AnswerForm", "AnswerNKI",null, new {id = "mylink"}))
then I made a new function:
$('#mylink').click(function (goalcard) {
var id = goalcard.Id;
this.href = this.href + '/' + id;
});
This should work, but what happens is that I have to use this click function inside the forEach loop to be able to reach to goalcard variable. and If I put it inside the forEach, this Click function will get executed many times depending on how many goalcard there are.
So the result would be /AnswerNKI/AnswerForm/1/2 if there are two goalcards.
or maybe /AnswerNKI/AnswerForm/1/2/3/4/5 if there are five goalcards.
But it should be /AnswerNKI/AnswerForm/1
it basically adds up.
Another problem is that all other rows have /AnswerNKI/AnswerForm/ so only the first row basically gets an id.
I have no idea how to find a solution to fix that.
Any kind of help is very appreciated.
Thanks in advance
This isn't a solution to the specific problem you're having. But it looks like you're using jquery to update part of your page.
If so, have you considered using a callback which returns html generated by a PartialView, and just doing a replace within the javascript callback? That's a pattern I use a lot. It allows you to use the MVC engine, components and design tools.
Here's an example of something I do:
$("form.unscoped_filter").live("submit", function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
error: function (a, b) {
debugger;
},
success: function (result) {
$("div#targetID").html(result);
bindExtenders();
}
});
return false;
});
This particular example intercepts a postback from a particular class of forms and passes it on to the website where it's processed by my MVC app. The target method and controller are set, per usual MVC design approaches, in a BeginForm block. The target method processes data and returns a PartialView which translates that data into html, which in turn is sent to the success callback in the jquery block. There it's used to replace the html within the target div. While there are more parts in play (e.g., the javascript, the MVC method, the PartialView), separating things this way lets each part play to its unique strengths: jquery is wonderful at manipulating the DOM, MVC methods are great at manipulating/processing requests for html, and PartialViews are a great tool for laying out and generating html.
This is a pretty flexible and powerful approach once you get the hang of it. In particular, you can pass parameters into the jquery block from the ActionLink by using html5 techniques. For example, you can add a "data-someParamName=..." to the html attributes of the ActionLink call, and then extract the parameter value within the javascript block doing something like:
var pagerCode = $(this).attr("data-someParamName");
That, in fact, is how I control which particular div gets updated in the success callback function.
Again, this doesn't answer your specific question so much as suggest a different way of tackling what I think you're trying to do. Good luck!

Using jQuery getJSON and fire a function AFTER the results have been processed... should work... but doesn't

I have a series of functions which populate a series of drop down boxes.
This is a product data page, and serves both to add a new item, or edit an existing one. In the latter case, once all the drop down boxes are populated, it grabs an item data from a database as a JSON string and selects the appropriate values in the drop down bozes using $('#elem').val('value')
This all works fine, except I can't get it to things in the right order.
1. function loadBrands() {
2. $('#brand').empty().append('<option value="">Select...</option>').addClass('centreLoader');
3. $.getJSON('/jsonData/brands.txt', function (data) {
4. $.each(data, function (i, item) {
5. $('#brand').append('<option value="' + data[i].label + '">' + data[i].brandName+ '</option>');
6. });
7. $('#brand').removeClass('centreLoader');
8. loadSavedItem();
9. });
10. };
I've added line numbers to explain simply (although you'll all know what this does!)
Line 3 gets the JSON data from my file (this is valid data as it populates fine), then line 4 begins looping the data returned and populating the drop down.
Line 8 is where things go wrong, this calls the function loadSavedItem which looks a bit like this:
1. function loadSavedItem(thisItemId) {
2. $.getJSON('/jsonData/QUERY_DB_FOR_THIS_PRODUCT (thisItemId)', function (data) {
3. $('#brand').val(data[0].brand);
4. });
5. };
Again, pretty simple, line 2 gets the JSON output (which is again valid, it populates other fields fine) and sets the field values as applicable (this is obviously a shortened version of the code)
The problem appears to be that loadSavedItem() is being called too soon, before #brands is fully populated, so it cannot set the value correctly. If I put a time delay in, then it works.
BUT... I thought that anything after the $(each... jQuery statement should not happen until $(each) has finished?
How can I ensure that this is the case?
In my experience, $(each) can loop while the rest of the script is running, if that makes sense (in Chrome, at least). Maybe it's something to do with "optimisation".
I've solved this problem before by checking data.length, setting a counter that increments by one and then firing the code off if the counter equals the length.
function loadBrands() {
$('#brand').empty().append('<option value="">Select...</option>').addClass('centreLoader');
$.getJSON('/jsonData/brands.txt', function (data) {
var dataNum = data.length;
var counter = 1;
$.each(data, function (i, item) {
$('#brand').append('<option value="' + data[i].label + '">' + data[i].brandName+ '</option>');
if (dataNum == counter) {
$('#brand').removeClass('centreLoader');
loadSavedItem();
}
counter ++;
});
});
}
My suggestion would be to add the method "loadSavedItem()" in the Success function something like below. This should solve the problem.
$.ajax({
url: url,
dataType: 'json',
async: true,
data: myData,
success: function(data) { // loadSavedItem(); }
});
Hope this Helps!!
I believe the clue is async setting for jQuery.ajax().
http://api.jquery.com/jQuery.ajax/

Value of html from jquery get

I want to retrieve the value of a text field on a another page on my website (prices.html)
Using http://api.jquery.com/jQuery.get/, how can I accomplish this?
How can I do this?
var price = $('input:price').val(); <- the value of price from prices.html (i'm not on this page so i need to request it)
How can I do this?
Thanks in advance.
You could try .load().
.load('price.html input[name="price"]', function(data) {
alert(data);
});
I didn't try it out myself, but it should work.
One of the last examples on the jQuery get page provides you a clue:
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Assuming that you get your page correctly, you should get a data payload, which you can then parse to get the price information that you're looking for. Using another example, if you have your data processed as JSON, you can extract data like so:
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json");
Without more information, it'll be hard to put together a working example.
Before you live prices.html page, will be good to store/transfer (post/get) input:price in hidden textfield in new page and than read hidden textfield with jquery

Categories

Resources