5

I have a JSON array in the format like this

 "StoreName":["10001 Main ST","10002 Part1","10004 MyStore1","10005 M STR",        "10008 Centro","10009 MyStore 02","1001 G","1001 H","10010 Store main ROAD","10011 Central M Store","10012 En Department","10013 M Station","10014 Test Center","10015 SubStore1","10016 AA","10018 M part #","10019 Test A - 26032016","1002 B","1002 I","10020 Test Central B "]

and I have to access each element of it and display it into options in select tag as

<select id ="storeNm" name="name">
  <option>--Select--</option>
  <option>---Here store name list contents---</option>
  <option>---Here store name list contents---</option>
</select>

I am new to JSON and have to do it using javascript/jQuery so any help/guidance will be appreciated.

3
  • use .each to loop through your list and use append to insert selected into the select\ Commented Oct 13, 2016 at 6:05
  • how can I do that can you show it with an example? @guradio Commented Oct 13, 2016 at 6:27
  • see below answer it covers all your requirements Commented Oct 13, 2016 at 6:54

1 Answer 1

8

Iterate and generate elements using Array#map method. Where elements can be generate using jQuery.

var data = {
  "StoreName": ["10001 Main ST", "10002 Part1", "10004 MyStore1", "10005 M STR", "10008 Centro", "10009 MyStore 02", "1001 G", "1001 H", "10010 Store main ROAD", "10011 Central M Store", "10012 En Department", "10013 M Station", "10014 Test Center", "10015 SubStore1", "10016 AA", "10018 M part #", "10019 Test A - 26032016", "1002 B", "1002 I", "10020 Test Central B "]
};

// create select tag
$('<select/>', {
  // set id of the element
  id: 'storenm',
  // generate html content by iterating over array
  html: data.StoreName.map(function(v) {
      // generate option with value and text content
      return $('<option>', {
        text: v,
        value: v
      });
    })
    // append the generated tag to body
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

8 Comments

Nice answer. But I suppose, besides text, having a value for the option would be nice to have.
@ThomasJunk : added value for option :)
I have used code snippet in script tag and even given the link for jQuery library but cant see the options as in the data list @PranavCBalan
@ShreyaRawal : if you want to update options in existing select tag then do it like jsfiddle.net/pranavcbalan/w2ps6zn8/1 ...... or if you want to append then use append instead od html
@ShreyaRawal : although wrap your code with document ready handler always
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.