当前位置:网站首页>Native JS obtains form data and highlights and beautifies JSON output display
Native JS obtains form data and highlights and beautifies JSON output display
2022-06-25 14:19:00 【jason_ renyu】
Now the basic projects are mainly based on the framework react and vue And so on , This has led to a lot of people's concern about native js The operation of becomes rusty , Even the front-end foundation of some people who have worked for several years is still half understood , You can talk freely when you ask about the framework , Face primordial js And then he hesitated .
A good framework always attracts a lot of fans to follow , But the original charm also needs us to understand , The framework is easy to use, but the basic knowledge should also keep up , The same is not much to say, directly on the code :
serialize.js
// Get developed form All form elements in
const getFormElements = (formId) => {
const form = document.getElementById(formId);
const tagElements = form.querySelectorAll('input,select,textarea');
if (tagElements.length > 0) {
return Array.from(tagElements);
}
try {
console.error(new Error(' At present form No form content , Please check and try again '));
} catch (error) {
console.log(error);
}
return false;
}
// Get single or multiple choices Selected value
const getInputSelector = (ele) => {
if (ele.checked) {
return [ele.name, ele.value];
}
}
// obtain input data
const getInputData = (ele) => {
const type = ele.type.toLowerCase();
if (['text', 'password', 'number', 'file', 'color', 'hidden', 'date','search','email','tel','url']) {
return [ele.name, ele.value];
} else if (['checkbox', 'radio'].includes(type)) {
return getInputSelector(ele);
}
return false;
}
// Collating data
const serializeFormData = (ele) => {
let result = [];
if (['select', 'textarea'].includes(ele.tagName.toLowerCase())) {
result = [ele.name, ele.value];
} else {
result = getInputData(ele);
}
if (result && result[0]) {
return result;
}
return false;
}
// How to get data
const serializeForm = (formId) => {
const eles = getFormElements(formId);
const results = {
};
if (!eles) return results;
for (let i = 0; i < eles.length; i++) {
const tempData = serializeFormData(eles[i]);
if (tempData) {
const key = tempData[0];
const value = tempData[1];
if (results[key]) {
if (typeof results[key] === 'object') {
results[key].push(value);
} else {
results[key] = [results[key], value];
}
} else {
results[key] = value;
}
}
}
return results;
}
Examples of use html Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Native js obtain form data </title>
<style> pre {
outline: 1px solid #ccc; padding: 5px; margin: 5px; background-color: #f5f5f5; } .string {
color: green; } .number {
color: darkorange; } .boolean {
color: blue; } .null {
color: magenta; } .key {
color: red; } </style>
</head>
<body>
<form id="loginForm">
user name 1:
<input type="text" name="username"><br />
user name 2:
<input type="text" name=""><br />
password :
<input type="password" name="password"><br />
Gender :
<label><input type="radio" name="sex" value="nan"> male </label>
<label><input type="radio" name="sex" value="nv"> Woman </label><br />
hobby :
<label><input type="checkbox" name="hobby" value="baseball"> Basketball </label>
<label><input type="checkbox" name="hobby" value="football"> football </label>
<label><input type="checkbox" name="hobby" value="pingbang"> Table Tennis </label><br />
City :
<select name="city">
<option value="zhengzhou"> zhengzhou </option>
<option value="luoyang"> luoyang </option>
<option value="nanjing"> nanjing </option>
<option value="shanghai"> Shanghai </option>
</select><br />
Birthday :
<input type="date" name="birthday"><br />
Like color :
<input type="color" name="color"><br />
Upload photos :
<input type="file" name="file"><br />
Content :
<textarea name="content" cols="30" rows="10"></textarea>
<br />
<!-- Hidden information -->
<input type="hidden" name="phone" value="12345678901">
<input type="button" onclick="submitFormData()" value=" Submit ">
</form>
<!-- -->
form Form content :
<pre id="formData">
</pre>
</body>
<script src="./serializeForm.js"></script>
<script> // Highlight beautification JSON Output shows function syntaxHighlight(json) {
// With lock in JSON if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2); } // to JSON Add display style to the string json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number'; if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key'; } else {
cls = 'string'; } } else if (/true|false/.test(match)) {
cls = 'boolean'; } else if (/null/.test(match)) {
cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; }); } function submitFormData() {
const formData = serializeForm('loginForm'); console.log(' At present form Data and information ', formData); if (formData) {
document.getElementById('formData').innerHTML = syntaxHighlight(formData); } } </script>
</html>
Highlight beautify output JSON
// Highlight beautification JSON Output shows
function syntaxHighlight(json) {
// With lock in JSON
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
// to JSON Add display style to the string
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
If you don't want to beautify , Just use this line
JSON.stringify(json, undefined, 2);
My blog is characterized by , Less nonsense, information is in the code , Leave a message if you have any questions , You can also go to QQ Discuss with the group :
QQ Group 1: 657011407, QQ Group 2: 492593055, You can also find me on wechat shenzhipeng1023
边栏推荐
- Is it safe for Guosen Securities to open a stock account? Excuse me?
- 多台云服务器的 Kubernetes 集群搭建
- Two methods to rollback the code in pycharm to the specified version (with screenshot)
- Hash table, hash conflict
- Shell array
- Renix Perf: IP网络性能测试工具及测试用例参数详解
- JS component
- 测一测你的挣钱能力有多强?未来的你将从事什么职业?
- Numpy库使用入门
- Discriminative v.s.Generative
猜你喜欢

Test your earning power? What will you do in the future?

程序员为什么要软一点?

k线图24种经典图解(影线篇)

'NVIDIA SMI' is not an internal or external command, nor is it a runnable program or batch file

Experts' suggestions | 8 measures to accelerate your innovative career planning and growth

Getting started with shell variables

多台云服务器的 Kubernetes 集群搭建

中国电池技术取得重大突破,日韩美都落后了,中国巩固了领先优势

完整详细的汇编实验报告

作为一名软件测试工程师你认为怎么样才能保证软件质量?
随机推荐
国信证券股票账户开户安全吗?请问。
解决报错:Creating window glfw ERROR: GLEW initalization error: Missing GL version
Is it safe for Guosen Securities to open an account?
多台云服务器的 Kubernetes 集群搭建
分享自己平时使用的socket多客户端通信的代码技术点和软件使用
oracle数据库常用的函数总结
一次性总结:64个数据分析常用术语!
Output 0 ~ n digits and output multiple times
数据采集系统网关采集工厂效率
让PyTorch训练速度更快,你需要掌握这17种方法
One time summary: 64 common terms for data analysis!
Table de hachage, conflit de hachage
It's not easy to understand the data consistency of the microservice architecture for the first time after six years as a programmer
Discriminative v.s.Generative
权益NFT开创者Hash Eagle如何重新定义NFT,用权益赋能长续价值?
Page 112 machine learning - review of fundamentals of mathematics pptx
Nine parts of speech and nine tenses in English
哈希表、哈希冲突
Getting started with shell variables
turtlebot+lms111+gmapping实践