Html select from json

jQuery Select Option from Json

* You might ask isn’t jQuery javascript? Yes indeed you are right, but jQuery is a framework making javascript programming a lot easier.

When I say plain javascript, or as some are calling it old school javascript, I meant to use the same task without using jQuery.

What select box is and types of select box options

Select box is one of the most used HTML element along with text input, radio option and the like.

Select box will allow you to provide dropdown options where you can select one or more items from it. You can make the select box to allow multiple selection using multiple attribute

The above is multi select that you can select multiple options by holding ctrl keyboard if you are on windows and command button if you are on windows.

Here is the code to create multi select box

   

As you can see on the example, adding multiple attribute in select tag would change the select box into multi select box.

Here is an example of select box option that is not multi

Читайте также:  Stringbuilder java добавить в начало

What is JSON and what is its use?

JSON stands for Javascript Object Notation. It is standard format for sending and getting data to and from web server.

It is like having a common format for sending request and getting data back. JSON is not language or browser specific. As long as you can run javascript on the browser, you can process it.

The general format of JSON looks like

Enclose the key and values with in quote, “, and have curly braces at the front and back of the data. This is standard for non array data.

And for array data you will have:

[«php», «java», «javascript», «ruby», «go», «shell», «c#», «python», «perl»]

The above should work fine as long as you are not having any key value kinda of relation in the data. If you have one, then make sure to enclose one with in curly bracket

That way, each added ones would considered as objects.

Accessing JSON elements with jQuery

I will be focusing on array data of jQuery since those are the most common types to interact with.

So, the first step in populating the select options would be reading the JSON data itself first.

Lets say the json data looks like this:

In the above example the key could be a database id the server sent and we will populate the options based on that.

   

Once we know how to access the values, then it would be a matter of gluing all together to populate jquery select option.

   

From the above example, the populated_options contains all the options that are read from the JSON array.

The final step on jQuery select option tutorial would be assigning this option text to the select box of our choice.

Lets say, for the purpose of jQuery select option tutorial, there is a select box with id programming_languages_select.

Then to populate the options

 var programming_languages = []; $('#programming_languages_select').append(produceOptions(programming_languages)) 

The above snippet would populate the select box with appropriate key values and that would conclude the jquery select option tutorial.

Источник

Overview

A common requirement when developing forms on the web is populating a dropdown list using data from a web service or external file.

Suppose we have a form that asks the user for their country followed by the state or province (if applicable). We would want the country selection to determine the list of states/provinces that are displayed.

Screenshot of dropdown list

In this article, we’ll walk through code that populates a dropdown using sample JSON data containing Canadian province names and abbreviations.

Sample Data

Our sample data can be found at MyJSON with the following contents:

We’ll use the names for the contents of the elements and the abbreviation for the values.

Solutions

The following solutions manipulate the DOM by populating an HTML select element we’ve defined on our page:

Our task can be divided into four steps:

  1. Target the dropdown
  2. Clear any existing options
  3. Insert a default option named «Choose State/Province» which is shown as a visual cue
  4. Insert an option for each province found in the JSON data

jQuery

let dropdown = $('#locality-dropdown'); dropdown.empty(); dropdown.append(''); dropdown.prop('selectedIndex', 0); const url = 'https://api.myjson.com/bins/7xq2x'; // Populate dropdown with list of provinces $.getJSON(url, function (data) ').attr('value', entry.abbreviation).text(entry.name)); >) >);
  • Line 1 targets the select element
  • Line 3 clears any options in the element
  • Lines 5-6 appends our default option
  • Line 8 defines the URL where we can find our JSON data
  • Lines 11-15 fetch the data and populate the options according to our requirements

Vanilla JavaScript

Some developers avoid jQuery for performance reasons, so we’ve included two vanilla JavaScript solutions as well. This code is more verbose because we don’t have the getJSON method at our disposal.

Using XMLHttpRequest

let dropdown = document.getElementById('locality-dropdown'); dropdown.length = 0; let defaultOption = document.createElement('option'); defaultOption.text = 'Choose State/Province'; dropdown.add(defaultOption); dropdown.selectedIndex = 0; const url = 'https://api.myjson.com/bins/7xq2x'; const request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function() < if (request.status === 200) < const data = JSON.parse(request.responseText); let option; for (let i = 0; i < data.length; i++) < option = document.createElement('option'); option.text = data[i].name; option.value = data[i].abbreviation; dropdown.add(option); >> else < // Reached the server, but it returned an error >> request.onerror = function() < console.error('An error occurred fetching the JSON from ' + url); >; request.send();
  • Line 1 targets the select element
  • Line 2 clears any options in the element
  • Lines 4-5 appends our default option
  • Line 10 defines the URL where we can find our JSON data
  • Lines 12-13 initializes the remote request
  • Lines 19-24 creates an option element for each entry found and adds it to the select list
  • Line 34 sends the remote request

Using Fetch

let dropdown = document.getElementById('locality-dropdown'); dropdown.length = 0; let defaultOption = document.createElement('option'); defaultOption.text = 'Choose State/Province'; dropdown.add(defaultOption); dropdown.selectedIndex = 0; const url = 'https://api.myjson.com/bins/7xq2x'; fetch(url) .then( function(response) < if (response.status !== 200) < console.warn('Looks like there was a problem. Status Code: ' + response.status); return; >// Examine the text in the response response.json().then(function(data) < let option; for (let i = 0; i < data.length; i++) < option = document.createElement('option'); option.text = data[i].name; option.value = data[i].abbreviation; dropdown.add(option); >>); > ) .catch(function(err) < console.error('Fetch Error -', err); >);

Источник

jQuery Select Option from Json

* You might ask isn’t jQuery javascript? Yes indeed you are right, but jQuery is a framework making javascript programming a lot easier.

When I say plain javascript, or as some are calling it old school javascript, I meant to use the same task without using jQuery.

What select box is and types of select box options

Select box is one of the most used HTML element along with text input, radio option and the like.

Select box will allow you to provide dropdown options where you can select one or more items from it. You can make the select box to allow multiple selection using multiple attribute

The above is multi select that you can select multiple options by holding ctrl keyboard if you are on windows and command button if you are on windows.

Here is the code to create multi select box

   

As you can see on the example, adding multiple attribute in select tag would change the select box into multi select box.

Here is an example of select box option that is not multi

What is JSON and what is its use?

JSON stands for Javascript Object Notation. It is standard format for sending and getting data to and from web server.

It is like having a common format for sending request and getting data back. JSON is not language or browser specific. As long as you can run javascript on the browser, you can process it.

The general format of JSON looks like

Enclose the key and values with in quote, “, and have curly braces at the front and back of the data. This is standard for non array data.

And for array data you will have:

[«php», «java», «javascript», «ruby», «go», «shell», «c#», «python», «perl»]

The above should work fine as long as you are not having any key value kinda of relation in the data. If you have one, then make sure to enclose one with in curly bracket

That way, each added ones would considered as objects.

Accessing JSON elements with jQuery

I will be focusing on array data of jQuery since those are the most common types to interact with.

So, the first step in populating the select options would be reading the JSON data itself first.

Lets say the json data looks like this:

In the above example the key could be a database id the server sent and we will populate the options based on that.

   

Once we know how to access the values, then it would be a matter of gluing all together to populate jquery select option.

   

From the above example, the populated_options contains all the options that are read from the JSON array.

The final step on jQuery select option tutorial would be assigning this option text to the select box of our choice.

Lets say, for the purpose of jQuery select option tutorial, there is a select box with id programming_languages_select.

Then to populate the options

 var programming_languages = []; $('#programming_languages_select').append(produceOptions(programming_languages)) 

The above snippet would populate the select box with appropriate key values and that would conclude the jquery select option tutorial.

Источник

Оцените статью