jQuery plugin to serialize a form and also restore/populate the form?

前端 未结 8 2080
花落未央
花落未央 2020-12-02 08:40

Is there a jQuery plugin out there that can serialize a form, and then later restore/populate the form given the serialized value? I know the form plugin can serialize as a

8条回答
  •  时光说笑
    2020-12-02 09:10

    • Support multiple inputs with same name (checkboxes usually do this).
    • Cache selectors when possible
    • Return values for all inputs, if checkbox or radio isn't set, the value is null
    • Deactivates checkbox or radio if value is null

      $.fn.formData = function(values) {
        var form = $(this);
        var inputs = $(':input', form).get();
        var hasNewValues = typeof values == 'object';
      
        if (hasNewValues) {
          $.each(inputs, function() {
            var input = $(this);
            var value = values[this.name];
      
            if (values.hasOwnProperty(this.name)) {
              switch (this.type) {
                case 'checkbox':
                  input.prop('checked', value !== null && value);
                  break;
                case 'radio':
                  if (value === null) {
                    input.prop('checked', false);
                  } else if (input.val() == value) {
                    input.prop("checked", true);
                  }
                  break;
                default:
                  input.val(value);
              }
            }
          });
          return form;
        } else {
          values = {};
          $.each(inputs, function() {
            var input = $(this);
            var value;
            switch (this.type) {
              case 'checkbox':
              case 'radio':
                value = input.is(':checked') ? input.val() : null;
                break;
              default:
                value = $(this).val();
            }
            values[this.name] = value;
          });
          return values;
        }
      };
          

提交回复
热议问题