-1

I have the following JSON:

{"a":"111","b":"7"}

Also, I have a selectbox with value (a and b). I want to make it when user select "a", it will show "111" from the JSON while select "b", it will show "7".

I wrote the following jQuery, but the JSON value returned out is undefined.

<select id="selectbox" name="selectbox">
            <option value="a" grouping="">A</option>
            <option value="b" grouping="">B</option>
</select>

The field store the JSON value:

<input id="JSON" name="JSON" type="text" value="{"SickLeave":"111","AnnualLeave":"7"}">

My jQuery code:

$("select[name=selectbox]").on('change', function() {

      var obj = JSON.parse($('[name$=JSON]').val());
      var optionvalue = $("select[name=selectbox] option:selected").val();

      console.log(optionvalue);
      console.log(obj.optionvalue);
});

However, the "obj.optionvalue" is undefined.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Tommy Mok
  • 91
  • 10
  • 4
    Hint: look at the quotes in the `value` attribute where you put the JSON.. – Rory McCrossan Feb 03 '20 at 17:32
  • You don't have a property on your `obj` named `optionvalue`. See https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable for solutions to that problem. – Heretic Monkey Feb 03 '20 at 17:49

1 Answers1

-1

This can help: First you have to replace {"SickLeave": "111", "AnnualLeave": "7"} by {"a": "111", "b": "7"} which has the structure of the JSON you used in the javascript code. Also as mentioned by @Rory McCrossan in his comment it was necessary to differentiate brakets that wrap up the value and those used in the json as follows: value='{"a":"111","b":"7"}' Since optionvalue is a variable, the most correct way to access the value of the attribute of the json having le value of optionvalue as key is to do the following:obj[optionvalue] instead of obj.optionvalue

<select id="selectbox" name="selectbox">
  <option value="a" grouping="">A</option>
  <option value="b" grouping="">B</option>
</select>
<input id="JSON" name="JSON" type="text" value='{"a":"111","b":"7"}'>

<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>

  <script>
    $("select[name=selectbox]").on('change', function() {

      var obj = JSON.parse($('[name$=JSON]').val());
      var optionvalue = $("select[name=selectbox] option:selected").val();

      console.log(optionvalue,obj);
      console.log(obj[optionvalue]);
   });
    </script>