0

Below is how I am capturing and saving the values of my web form to JSON, using the name attribute and values.

How can I repopulate the form from my captured JSON data in the same format using name and value. (context: I will stash the saved json, and call it later to repopulate said form)

My code to save the values as JSON:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('form#saveTemp').submit(function() {
        alert(JSON.stringify($('form').serializeObject()));
        return false;
    });
});

A jsfiddle of it.

1
  • Note that Stack Snippets would allow people to run the code without leaving Stack Overflow... Commented Mar 18, 2020 at 14:27

1 Answer 1

1

check this i already used for my project with help jquery.serialize concept

Concepts:

  1. You can use value.But for some case value not accessible use with data-value instead
  2. And if you need special class with special action check with elem.hasClass method

$.fn.serializeObject = function() {
  var arr = $(this).find('input,textarea,select').map(function(a, elem) {
    if ($.trim($(elem).attr('name'))) {
      if ($(elem).is('input[type=radio]') || $(elem).is('input[type=checkbox]')) {
        if ($(elem).is(':checked')) {
          return ({
            [$(elem).attr('name')]: $(elem).attr('data-value') ? $.trim($(elem).attr('data-value')) : $.trim($(elem).val())
          });
        } else {
          if ($(elem).is('input[type=checkbox]')) {
            return ({
              [$(elem).attr('name')]: ""
            });
          }
        }
      } else if ($(this).hasClass('datepicker')) {
        return ({
          [$(elem).attr('name')]: ($(elem).val().trim() ? $(elem).val().toString().split('-').reverse().join('-') : "")
        });
      } else {

        return ({
          [$(elem).attr('name')]: $(elem).attr('data-value') ? $.trim($(elem).attr('data-value')) : $.trim($(elem).val())
        });
      }
    }
  }).get();
  arr = arr.reduce((a, b) => (a[Object.keys(b)[0]] = Object.values(b)[0], a), {});
  return arr;
}

$(function() {
  $('form#saveTemp').submit(function() {
    alert(JSON.stringify($('form').serializeObject()));
    return false;
  });
});
form {
  line-height: 2em;
}

p {
  margin: 5px 0;
}

h2 {
  margin: 10px 0;
  font-size: 1.2em;
  font-weight: bold
}

#result {
  margin: 10px;
  background: #eee;
  padding: 10px;
  height: 40px;
  overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="saveTemp">
  <div id='polygon-styles' class='clear' data-bind="visible:polygonFeature">
    <div class="left">

      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Style Name</label>
        </div>
        <div class="left">
          <input id='style-name' class='w150' type="text" data-text-field="name" data-value-field="value" name="styleName">
        </div>
      </div>

      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Fill Type</label>
        </div>
        <div class="left">
          <select id='style-type' class='w150' data-role="dropdownlist" data-bind="source:pgFillTypes,value:pgFillType" data-text-field="name" data-value-field="value" name="fillType">
          </select>
        </div>
      </div>
      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Fill Color</label>
        </div>
        <div class="left">
          <input class="w100" data-role="colorpicker" data-bind="value:pgFillColor,enabled:pgFillColActive" name="fillColor">
        </div>
      </div>
      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Transparency</label>
        </div>
        <div class="left">
          <input type='number' class='w100' data-role="numerictextbox" data-format="p" data-min="0" data-max="1" data-step="0.1" data-bind="value:pgFillTrans,enabled:pgFillTransActive" name="fillTrans" />
        </div>
      </div>
    </div>
    <div class="left">
      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Outline Type</label>
        </div>
        <div class="left">
          <select id='polygon-outline-style-type' class='w150' data-role="dropdownlist" data-bind="source:plTypes,value:pgOutlineType" data-text-field="name" data-value-field="value" name="outlineType">
          </select>
        </div>
      </div>
      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Outline Width</label>
        </div>
        <div class="left">
          <input type='number' class='w100' data-role="numerictextbox" data-format="n" data-min="1" data-bind="value:pgOutlineWidth" name="outlineWidth" />
        </div>
      </div>
      <div class="marg clear of-h">
        <div class="w100 left">
          <label>Outline Color</label>
        </div>
        <div class="left">
          <input class="w100" data-role="colorpicker" data-bind="value:pgOutlineColor" name="outlineColor">
        </div>
      </div>

      <button class="save-temp-btn" input type="submit" value="submit">Save as Template</button>

      <div class="left">
        <div class="marg clear of-h">
          <div class="w100 left">
            <label>Apply Shared Template</label>
          </div>
          <div class="left">
            <select id='polygon-shared-templates' class='w150' data-role="dropdownlist" data-bind="" data-text-field="name" data-value-field="value">
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
  
<button type="submit" id="populateForm">Populate
        </button>
</form>

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

5 Comments

Thanks! However I just ran it, entered some values -> hit 'save as template' -> removed the values, and hit -> 'populate' button and it did not populate.
set populate button type='submit'.And wrap with in form same like save as template button
Thanks.. that change still didn't populate it
yeah it's still not populating.. but thanks for the response, +1 anyway
I am running it directly above in SO from your snippet!

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.