2

I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output. Help about where I am going wrong is much appreciated!

HTML

<script>
var select, option, arr, i;
function loadJSON(var x){
    if(x.match == "A"){
        array = JSON.parse(ACodes);
        select = document.getElementById('dd1');

        for (i = 0; i < array.length; i++) {
          option = document.createElement('option');
          option.text = array[i]["Code"];
          select.add(option);
        }
    }

    else if(x.match == "B"){
        array = JSON.parse(BCodes);
        select = document.getElementById('dd2');

        for (i = 0; i < array.length; i++) {
          option = document.createElement('option');
          option.text = array[i]["Curr"];
          select.add(option);
        }
    }


}
</script>

<body onload="loadJSON('A');laodJSON('B')">
    <select id="dd1"></select>
    <select id="dd2"></select>
</body>

JSON

ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
6
  • Use the debugging tools in your browser (developer tools > console). You have a syntax error on the second line of your script. jshint.com is also useful for that. Commented Jul 24, 2015 at 10:52
  • laodJSON is wrong in your body.onload and I think you have to remove the whitespace in your ACodes. Also, where are these JSON variables declared? Could you take this whole thing and put it into a SO snippet? Commented Jul 24, 2015 at 10:53
  • @somethinghere — How is loadJSON "wrong" there? There is no limit on whitespace between pieces of data in JSON. Commented Jul 24, 2015 at 11:02
  • @Quentin Look again: laodJSON . Heres an expanded version: <body onload="loadJSON('A');laodJSON('B')">. See the issue? Also, you could be right about the JSON thing. Commented Jul 24, 2015 at 11:03
  • @somethinghere — Oh, spelling error. That wasn't obvious. :) Commented Jul 24, 2015 at 11:05

4 Answers 4

2
  1. remove var at loadJSON(var x) => loadJSON(x)
  2. remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
  3. laodJSON('B'); at body onload is typo.

  4. There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.

<body onload="  loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>

<script>
var select, option, arr, i;
  var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
  var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
  var array, select, target;
  if (x === 'A') {
    array = JSON.parse(ACodes);
    select = document.getElementById('dd1');
    target  = 'Code';
  } else if (x === 'B') {
    array = JSON.parse(BCodes);
    select = document.getElementById('dd2');
    target  = 'Curr';
  }
  
   for (i = 0; i < array.length; i++) {
      option = document.createElement('option');
      option.text = array[i][target];
      select.add(option);   
  }
} 
</script>
  </body>

Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.

// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
  var arr = JSON.parse(jsonObj);
  // Get by Id
  var select = document.querySelector('select#' + selectId);
  // Loop through array
  arr.forEach(function(item) {
    var option = document.createElement('option');
    option.text = item[key];
    select.add(option);
  });
}

// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
  // Get the target to append
  appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
  var arr = JSON.parse(jsonObj);
  // Create select and set id.
  var select = document.createElement('select');
  if (selectId != null) {
      select.id = selectId;
  }

  // Loop through array
  arr.forEach(function(item) {
    var option = document.createElement('option');
    option.text = item[key];
    select.add(option);
  });

  appendTarget.appendChild(select);
}
Sign up to request clarification or add additional context in comments.

7 Comments

thank you so much for your help! It was the typo that ruined it! :) Cheers!
any suggestions on how to make it more dynamic though? If possible?
Which parts do you want it to be more dynamic? Like, are you able to ensure that passed json all will have same key, and you can know their name? And do you want the select created when you passed the json, or you want to add options to target select?
yes I can ensure that the passed JSON will all have the same key, For e.g. If you consider ACodes, the key for all the elements in it will always be "Code" and similarly for BCodes, the key will always be "Curr".
Also, for the second part you asked, I could do either of them, as long as options are displayed when the select option dropdown is clicked.
|
1
<script>
 var select, option, arr, i;
 var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
 var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
 function loadJSON(x){

    if(x == "A"){
    array = JSON.parse(ACodes);
    select = document.getElementById('dd1');

    for (i = 0; i < array.length; i++) {
      option = document.createElement('option');
      option.text = array[i]["Code"];
      select.add(option);
    }
}

else if(x == "B"){
    array = JSON.parse(BCodes);
    select = document.getElementById('dd2');

    for (i = 0; i < array.length; i++) {
      option = document.createElement('option');
      option.text = array[i]["Curr"];
      select.add(option);
    }
}


}
</script>

<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>

Now this code will work.

The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.

I hope, This will help you.

1 Comment

you should not add 'var' when you are declaring parameter in function declaration.
0

You were well on your way, you just need to make it more dynamic :)

function loadOptions(json) {
    json = JSON.parse(json);

    var select = document.createElement('select'), option;
    for (var i = 0; i < json.length; i++) {
        for (var u in json[i]) {
            if (json[i].hasOwnProperty(u)) {
                option = document.createElement('option');
                option.text = json[i][u];
                select.add(option);

                break;
            }
         }
    }

    return select;
}

And to use it:

document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));

FIDDLE

http://jsfiddle.net/owgt1v2w/

2 Comments

You're rewritten the entire thing with the explanation "you just need to make it more dynamic". You haven't identified what was wrong with the original code at all,you just threw it away and started again.
my head got stuck when i saw I want to have one common JavaScript function. scumbag programmer mind just rewrote immediately :)
-1

The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)

Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html

Regards!

Comments

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.