简体   繁体   中英

Encoding and Decoding JSON in Hidden HTML element

I am trying to build a custom control using HTML and JQuery. The control will display a text value. The user can enter a variety of key/value pairs. Currently, I have the following HTML

<input id="keyValue" type="text" />
<select id="keyName" name="keyName">
  <option value="k1">Some Name</option>
  <option value="key2">Another Name</option>
  <option value="arg3">How about one more</option>
</select>
<input id="keyValuePairs" type="hidden" />

The value displayed in "keyValue" will change based on the option the user chooses. I'm trying to keep the mappings in keyValuePairs . In an attempt to do this, I have the following:

$('#keyName').on('change', function() {
  var key = $('#keyName').val();
  var keyValuePairs = $('#keyValuePairs').val();
  if (keyValuePairs[key]) {
    $('#keyValue').val(keyValuePairs[key]);
  } else {
    $('#keyValue').val('');
  }
});

$('#keyValue').on('change', function() {
  var key = $('#keyName').val();
  var keyValuePairs = $('#keyValuePairs').val();
  if (!keyValuePairs ) {
    keyValuePairs = {};
  }
  keyValuePairs[key] = $(this).val();
  $('#keyValuePairs').val(JSON.stringify(keyValuePairs));
});

For some reason, the text field always shows a blank string after I choose another key. I believe it has something to do with how I'm encoding or decoding the JSON. When I add console.log to the keyValuePairs I noticed that sometimes quotes are included and other times they're not. Yet, the code looks correct to me.

What am I doing wrong?

I believe you should JSON.parse $('#keyValuePairs').val() after you've read it (since you stringify the pairs when you set the value)

UPDATE:

You must also ensure that the value is not empty:

$('#keyName').on('change', function() {
    var key = $('#keyName').val();
    var val = $('#keyValuePairs').val();
    if (val && val.length > 0) {
        var keyValuePairs = JSON.parse(val);
        if (keyValuePairs[key]) {
            $('#keyValue').val(keyValuePairs[key]);
        } else {
            $('#keyValue').val('');
        }
    }
});

$('#keyValue').on('change', function() {
  var key = $('#keyName').val();
    var val = $('#keyValuePairs').val();
    var keyValuePairs;
    if (val && val.length > 0) {
        keyValuePairs = JSON.parse(val);
    } else {
        keyValuePairs = {};
    }
    keyValuePairs[key] = $(this).val();
    $('#keyValuePairs').val(JSON.stringify(keyValuePairs));
});
json_encode(#keyValuePairs)   //encoding
json_decode(#keyValuePairs)   //decoding
datatype : json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM