Baidu ueditor Rich Text - PC-side single, PC-side multiple, mobile-side single, mobile-side multiple

Keywords: Javascript Java JSP Mobile


We have done research on rich text plug-ins in previous articles.


Rich text plug-in


Ueditor

Baidu launched an open source online HTML editor.
http://fex-team.github.io/ueditor/



It's easy to use. We record its application process in detail in this chapter, as well as the specific configuration in different scenarios.



We have already applied the background framework of BootStrap on the basis of Spring MVC basic framework in previous articles, and recorded the usage of ueditor on this basis.

Applying bootstrap template


The source code download address of the basic project is:

Spring MVC+Shiro+MongoDB+BootStrap infrastructure


We have done a good job in the basic project home page index access.
Now we will modify the index.jsp page and index's Route Controller to implement ueditor usage.



Download Reference Plug-ins


The ueditor can be customized. We download the JSP version here:

http://ueditor.baidu.com/website/download.html


http://download.csdn.net/detail/q383965374/9887681





The zip package you downloaded is decompressed and the file is shown in the figure. You can use the browser to open index.html with a complete demo.





We create a new ueditor folder under the webapp path in the project and put all the extracted files into it, as shown in the figure:






The citation is as follows:

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>


ueditor.config.js is a configuration file where you can adjust the configuration and toolbar tools.





PC end single


Now let's initialize a rich text in the index.jsp page, and the content entered in the rich text is displayed on the PC side.


Introducing usage code

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>

Use placeholder code in html

     <script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;">
${pic.name}</script>


Initialization code, initialization with class name

// Initialize Text Editor
$(".ueditorFlag").each(function() {
    var id = this.id;    
    var ue = UE.getEditor(id, {
        pasteplain: true, /* Plain text pasting */
        autoHeightEnabled:false,/* Enable the right wheel, default is true automatic height mode*/
        toolbars: [[
          'fullscreen', 'source', '|', 'undo', 'redo', '|',
          'bold', 'italic', 'underline',
          'removeformat', '|',
          'insertorderedlist', 'insertunorderedlist',
          'indent', '|', 'justifyleft', 'justifycenter',
          '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', 'insertimage',
          '|', 'link', 'unlink'
      ]]
    }).addOutputRule(function(root){
      // Every time the edit box gets the focus, it will automatically insert <p><br/></p> if it is not needed, we can deal with it here.
    // Only the first empty paragraph is processed, and the subsequent paragraph may be added artificially.
    var firstPNode = root.getNodesByTagName("p")[0];
    firstPNode && /^\s*(<br\/>\s*)?$/.test(firstPNode.innerHTML()) && firstPNode.parentNode.removeChild(firstPNode);
    });
    console.log('ueditor for ' + id + ' init.');
});


In the same way as input, you can either form submission or retrieve values from js and submit them again. The parameter name passed to the background is the value of name.


Complete html

<%@ include file="./include/header.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>
        <div id="page-wrapper">
            <div id="page-inner">




                <div class="row">
                    <div class="col-md-12">
                        <h1 class="page-header">
              ueditor usage <small>PC End single</small>
                        </h1>
                    </div>
                </div>
                <!-- /. ROW  -->
  <div class="tab-pane fade active in">
          <form id="base">
            <div>
              <h4>Name</h4>
             <script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;">
${pic.name}</script>

            </div>
            <button type="button" class="btn btn-primary save">Preservation</button>
          </form>
        </div> 
                <!-- /. ROW  -->
            </div>
            <!-- /. PAGE INNER  -->
        </div>
        <!-- /. PAGE WRAPPER  -->


    


        
        




 <%@ include file="./include/footer.jsp"%>
<script type="text/javascript">








// Initialize Text Editor
$(".ueditorFlag").each(function() {
    var id = this.id;    
    var ue = UE.getEditor(id, {
        pasteplain: true, /* Plain text pasting */
        autoHeightEnabled:false,/* Enable the right wheel, default is true automatic height mode*/
        toolbars: [[
          'fullscreen', 'source', '|', 'undo', 'redo', '|',
          'bold', 'italic', 'underline',
          'removeformat', '|',
          'insertorderedlist', 'insertunorderedlist',
          'indent', '|', 'justifyleft', 'justifycenter',
          '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', 'insertimage',
          '|', 'link', 'unlink'
      ]]
    }).addOutputRule(function(root){
      // Every time the edit box gets the focus, it will automatically insert <p><br/></p> if it is not needed, we can deal with it here.
    // Only the first empty paragraph is processed, and the subsequent paragraph may be added artificially.
    var firstPNode = root.getNodesByTagName("p")[0];
    firstPNode && /^\s*(<br\/>\s*)?$/.test(firstPNode.innerHTML()) && firstPNode.parentNode.removeChild(firstPNode);
    });
    console.log('ueditor for ' + id + ' init.');
});








/**
 * jQuery form Extended access to data
 */
$.fn.formGet = function(opts) {
opts = $.extend({}, opts);
var data = {},
  els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]');
if (!els || !els.length) {
  return data;
}


var fnSetValue = (function(emptyToNull) {
  return emptyToNull ? function(obj, propertyChain, value, allowMulti) {
    value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)
  } : _fnObjectSetPropertyChainValue
})(opts.emptyToNull);


els.each(function() {
  var $this = $(this),
    type = $this.attr('type'),
    name = $this.attr('name'), // Possibly an attribute chain
    tag = this.tagName.toLowerCase();
  if (tag == 'input') {
    if (type == 'checkbox') {
      var v = $(this).val();
      if (v == 'on' || !v) {
        fnSetValue(data, name, $(this).prop('checked'));
      } else {
        $(this).prop('checked') && fnSetValue(data, name, v, true);
      }
    } else if (type == 'radio') {
      this.checked && fnSetValue(data, name, $this.val());
    } else {
      fnSetValue(data, name, $this.val());
    }
  } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {
    fnSetValue(data, name, $this.val());
  } else {
    fnSetValue(data, name, $.trim($this.text()));
  }
});
return data;
};




/**  
 * Internal Private Approach  
 */  
var _fnObjectGetPropertyChainValue = function(obj, propertyChain) {  
  /* Get the value of the attribute chain */  
  if (!obj) return;  
  if (!propertyChain) return obj;  
  var property,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!obj[property]) return;  
    obj = obj[property];  
  }  
  return obj[property];  
},  
_fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) {  
  /* Setting the value of the property chain */  
  if (!obj || !propertyChain) return;  
  var property,  
    chainObj = obj,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!chainObj[property]) {  
      chainObj[property] = {};  
    }  
    chainObj = chainObj[property];  
  }  
  // Improved version: checkbox's multiple options can be combined into arrays  
  if (!allowMulti || chainObj[property] === undefined) {  
    chainObj[property] = value;  
  } else {  
    var pv = chainObj[property];  
    if ($.isArray(pv)) {  
      pv.push(value);  
    } else {  
      chainObj[property] = [pv, value];  
    }  
  }  
  return obj;  
};  
  










  
    $(document).ready(function () {
        /*END-Save the form - END*/
        $('button.save').on('click', function () {
            debugger;
            var data = $('#base').formGet();
            $.ajax({
                type: "POST",
                url: "/pic/save",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (result) {
                    console.log(result);
                    if (!result.code) 
                    {
                        alert(result.data);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (result) {
                    alert("There was a mistake. Please try again later.");
                }
            });
        });
    });


</script>




</body>


</html>






Auxiliary Entities and Routing


Pic.java

package com.test.domain.entity;

import java.util.List;


public class Pic {
	private String id;
	private String name;
	private String description;
	private List<String> tags;//Label
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public List<String> getTags() {
		return tags;
	}
	public void setTags(List<String> tags) {
		this.tags = tags;
	}
	
	
}



IndexController.java

package com.test.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.domain.entity.Pic;
import com.test.util.JSONResult;

/**
 * IndexController
 * 
 * 
 */
@Controller
public class IndexController {

	@RequestMapping("/")
	public String index(Model model) throws IOException {
          model.addAttribute("hostname", "http://127.0.0.1:8080/");
          Pic pic=new Pic();
          List<String> tags=new ArrayList<String>();
          pic.setName("name");
          pic.setDescription("describe");
          tags.add("Football");
          tags.add("Baseball");
          tags.add("Basketball");
          pic.setTags(tags);
          model.addAttribute("pic", pic);
		return "/index";
	}

	
	@RequestMapping("/pic/save")
	@ResponseBody
	public JSONResult saveMigrateLine(@RequestBody Pic pic) {
		//Preserving pic records
		//int result = save(pic);
		int result =1;
		return result > 0 ? JSONResult.success("Save successfully")
				:JSONResult.error("Save failed!");
	}
}






PC end multiple

Because we use class for initialization here, it is very simple to add an additional input box, just add a placeholder code for the same class. As follows:

Their class es are ueditorFlag.

              <h4>Name</h4>
              <script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;">
${pic.name}</script>
              <h4>describe</h4>
  <script id="description" class="ueditorFlag" name="description" type="text/plain" style="width:100%;height:150px;">
${pic.description}</script>


It should be noted that when multiple scripts are used as placeholders, the id of script cannot be repeated with other element IDS in html, otherwise the page layout will be confused.


The effect is as follows:







mobile single


Previous single and multiple are aimed at the PC version of the initial use, and now Wechat public documents and mobile editors are also very common. In order to make the display of the simulated text more realistic on the page more beautiful on the mobile, we made some styling adjustments to the ueditor's style during initialization. Especially with the width limit.

style="width:375px;height:667px;"



Introducing usage code

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>

Use placeholder code in html

        <script id="content" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="content"></script>


Initialization code, initialization with class name

   function () {
            $(".ueditorFlag").each(function () {
                //Instance Editor
                var ue = UE.getEditor(this.id, {
                    pasteplain: true, /* Plain text pasting */
                    toolbars: [[
                        'fullscreen', 'source', '|', 'undo', 'redo', '|',
                        'bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|',
                        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|',
                        'link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                        'insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote'
                    ]],
                    iframeCssUrl: "/ueditor/themes/ancestry.css"
                });
                ue.ready(function() {
                    ue.setContent('${pic.description}');
                });
            });
        }

In the same way as input, you can either form submission or retrieve values from js and submit them again. The parameter name passed to the background is the value of name.


Complete html

<%@ include file="./include/header.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>
        <div id="page-wrapper">
            <div id="page-inner">


                <div class="row">
                    <div class="col-md-12">
                        <h1 class="page-header">
              ueditor usage <small>mobile End single</small>
                        </h1>
                    </div>
                </div>
                <!-- /. ROW  -->
  <div class="tab-pane fade active in">
          <form id="base">
            <div>
              <h4>content</h4>
                <script id="content" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="content"></script>
            </div>
            <button type="button" class="btn btn-primary save">Preservation</button>
          </form>
        </div> 
                <!-- /. ROW  -->
            </div>
            <!-- /. PAGE INNER  -->
        </div>
        <!-- /. PAGE WRAPPER  -->

    

        
        


 <%@ include file="./include/footer.jsp"%>
<script type="text/javascript">




$(document).ready(
        function () {
            $(".ueditorFlag").each(function () {
                //Instance Editor
                var ue = UE.getEditor(this.id, {
                    pasteplain: true, /* Plain text pasting */
                    toolbars: [[
                        'fullscreen', 'source', '|', 'undo', 'redo', '|',
                        'bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|',
                        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|',
                        'link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                        'insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote'
                    ]],
                    iframeCssUrl: "/ueditor/themes/ancestry.css"
                });
                ue.ready(function() {
                    ue.setContent('${pic.description}');
                });
            });
        }
)



/**
 * jQuery form Extended access to data
 */
$.fn.formGet = function(opts) {
opts = $.extend({}, opts);
var data = {},
  els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]');
if (!els || !els.length) {
  return data;
}

var fnSetValue = (function(emptyToNull) {
  return emptyToNull ? function(obj, propertyChain, value, allowMulti) {
    value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)
  } : _fnObjectSetPropertyChainValue
})(opts.emptyToNull);

els.each(function() {
  var $this = $(this),
    type = $this.attr('type'),
    name = $this.attr('name'), // Possibly an attribute chain
    tag = this.tagName.toLowerCase();
  if (tag == 'input') {
    if (type == 'checkbox') {
      var v = $(this).val();
      if (v == 'on' || !v) {
        fnSetValue(data, name, $(this).prop('checked'));
      } else {
        $(this).prop('checked') && fnSetValue(data, name, v, true);
      }
    } else if (type == 'radio') {
      this.checked && fnSetValue(data, name, $this.val());
    } else {
      fnSetValue(data, name, $this.val());
    }
  } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {
    fnSetValue(data, name, $this.val());
  } else {
    fnSetValue(data, name, $.trim($this.text()));
  }
});
return data;
};


/**  
 * Internal Private Approach  
 */  
var _fnObjectGetPropertyChainValue = function(obj, propertyChain) {  
  /* Get the value of the attribute chain */  
  if (!obj) return;  
  if (!propertyChain) return obj;  
  var property,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!obj[property]) return;  
    obj = obj[property];  
  }  
  return obj[property];  
},  
_fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) {  
  /* Setting the value of the property chain */  
  if (!obj || !propertyChain) return;  
  var property,  
    chainObj = obj,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!chainObj[property]) {  
      chainObj[property] = {};  
    }  
    chainObj = chainObj[property];  
  }  
  // Improved version: checkbox's multiple options can be combined into arrays  
  if (!allowMulti || chainObj[property] === undefined) {  
    chainObj[property] = value;  
  } else {  
    var pv = chainObj[property];  
    if ($.isArray(pv)) {  
      pv.push(value);  
    } else {  
      chainObj[property] = [pv, value];  
    }  
  }  
  return obj;  
};  
  





  
    $(document).ready(function () {
        /*END-Save the form - END*/
        $('button.save').on('click', function () {
            debugger;
            var data = $('#base').formGet();
            $.ajax({
                type: "POST",
                url: "/pic/save",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (result) {
                    console.log(result);
                    if (!result.code) 
                    {
                        alert(result.data);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (result) {
                    alert("There was a mistake. Please try again later.");
                }
            });
        });
    });

</script>


</body>

</html>





Auxiliary Entities and Routing


Pic.java

package com.test.domain.entity;

import java.util.List;


public class Pic {
	private String id;
	private String name;
	private String description;
	private List<String> tags;//Label
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public List<String> getTags() {
		return tags;
	}
	public void setTags(List<String> tags) {
		this.tags = tags;
	}
	
	
}



IndexController.java

package com.test.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.domain.entity.Pic;
import com.test.util.JSONResult;

/**
 * IndexController
 * 
 * 
 */
@Controller
public class IndexController {

	@RequestMapping("/")
	public String index(Model model) throws IOException {
          model.addAttribute("hostname", "http://127.0.0.1:8080/");
          Pic pic=new Pic();
          List<String> tags=new ArrayList<String>();
          pic.setName("name");
          pic.setDescription("describe");
          tags.add("Football");
          tags.add("Baseball");
          tags.add("Basketball");
          pic.setTags(tags);
          model.addAttribute("pic", pic);
		return "/index";
	}

	
	@RequestMapping("/pic/save")
	@ResponseBody
	public JSONResult saveMigrateLine(@RequestBody Pic pic) {
		//Preserving pic records
		//int result = save(pic);
		int result =1;
		return result > 0 ? JSONResult.success("Save successfully")
				:JSONResult.error("Save failed!");
	}
}


Design sketch





mobile multiple


mobile multiple is the same as PC multiple. class can be used to initialize. Limit the width of each edit box.

style="width:375px;height:667px;"


Reference plug-in

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>


html occupancy

  <div class="tab-pane fade active in">
          <form id="base">
            <div>
              <h4>content</h4>
                <script id="name" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="name">${pic.name}</script>
            </div>
             <div>
              <h4>describe</h4>
                <script id="description" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="description">${pic.description}</script>
            </div>
            <button type="button" class="btn btn-primary save">Preservation</button>
          </form>
        </div> 


setup code

$(document).ready(
        function () {
            $(".ueditorFlag").each(function () {
                //Instance Editor
                var ue = UE.getEditor(this.id, {
                    pasteplain: true, /* Plain text pasting */
                    toolbars: [[
                        'fullscreen', 'source', '|', 'undo', 'redo', '|',
                        'bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|',
                        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|',
                        'link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                        'insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote'
                    ]]
                });
            });
        }
)




Complete html code


<%@ include file="./include/header.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>
        <div id="page-wrapper">
            <div id="page-inner">


                <div class="row">
                    <div class="col-md-12">
                        <h1 class="page-header">
              ueditor usage <small>mobile End multiple</small>
                        </h1>
                    </div>
                </div>
                <!-- /. ROW  -->
  <div class="tab-pane fade active in">
          <form id="base">
            <div>
              <h4>content</h4>
                <script id="name" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="name">${pic.name}</script>
            </div>
             <div>
              <h4>describe</h4>
                <script id="description" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"
                                name="description">${pic.description}</script>
            </div>
            <button type="button" class="btn btn-primary save">Preservation</button>
          </form>
        </div> 
                <!-- /. ROW  -->
            </div>
            <!-- /. PAGE INNER  -->
        </div>
        <!-- /. PAGE WRAPPER  -->

    

        
        


 <%@ include file="./include/footer.jsp"%>
<script type="text/javascript">




$(document).ready(
        function () {
            $(".ueditorFlag").each(function () {
                //Instance Editor
                var ue = UE.getEditor(this.id, {
                    pasteplain: true, /* Plain text pasting */
                    toolbars: [[
                        'fullscreen', 'source', '|', 'undo', 'redo', '|',
                        'bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|',
                        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|',
                        'link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                        'insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote'
                    ]]
                });
            });
        }
)



/**
 * jQuery form Extended access to data
 */
$.fn.formGet = function(opts) {
opts = $.extend({}, opts);
var data = {},
  els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]');
if (!els || !els.length) {
  return data;
}

var fnSetValue = (function(emptyToNull) {
  return emptyToNull ? function(obj, propertyChain, value, allowMulti) {
    value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)
  } : _fnObjectSetPropertyChainValue
})(opts.emptyToNull);

els.each(function() {
  var $this = $(this),
    type = $this.attr('type'),
    name = $this.attr('name'), // Possibly an attribute chain
    tag = this.tagName.toLowerCase();
  if (tag == 'input') {
    if (type == 'checkbox') {
      var v = $(this).val();
      if (v == 'on' || !v) {
        fnSetValue(data, name, $(this).prop('checked'));
      } else {
        $(this).prop('checked') && fnSetValue(data, name, v, true);
      }
    } else if (type == 'radio') {
      this.checked && fnSetValue(data, name, $this.val());
    } else {
      fnSetValue(data, name, $this.val());
    }
  } else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {
    fnSetValue(data, name, $this.val());
  } else {
    fnSetValue(data, name, $.trim($this.text()));
  }
});
return data;
};


/**  
 * Internal Private Approach  
 */  
var _fnObjectGetPropertyChainValue = function(obj, propertyChain) {  
  /* Get the value of the attribute chain */  
  if (!obj) return;  
  if (!propertyChain) return obj;  
  var property,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!obj[property]) return;  
    obj = obj[property];  
  }  
  return obj[property];  
},  
_fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) {  
  /* Setting the value of the property chain */  
  if (!obj || !propertyChain) return;  
  var property,  
    chainObj = obj,  
    chains = propertyChain.split('.'),  
    i = 0,  
    len = chains.length;  
  for (;  
    (property = chains[i]) && i < len - 1; i++) {  
    if (!chainObj[property]) {  
      chainObj[property] = {};  
    }  
    chainObj = chainObj[property];  
  }  
  // Improved version: checkbox's multiple options can be combined into arrays  
  if (!allowMulti || chainObj[property] === undefined) {  
    chainObj[property] = value;  
  } else {  
    var pv = chainObj[property];  
    if ($.isArray(pv)) {  
      pv.push(value);  
    } else {  
      chainObj[property] = [pv, value];  
    }  
  }  
  return obj;  
};  
  





  
    $(document).ready(function () {
        /*END-Save the form - END*/
        $('button.save').on('click', function () {
            debugger;
            var data = $('#base').formGet();
            $.ajax({
                type: "POST",
                url: "/pic/save",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (result) {
                    console.log(result);
                    if (!result.code) 
                    {
                        alert(result.data);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (result) {
                    alert("There was a mistake. Please try again later.");
                }
            });
        });
    });

</script>


</body>

</html>


Other auxiliary classes are referred to above.



The effect is as follows:




Posted by spramod on Thu, 03 Jan 2019 22:06:10 -0800