search
HomeWeb Front-endJS TutorialHow to generate SQL query form using JavaScript_javascript skills

The example in this article describes the method of generating SQL query form using JavaScript. Share it with everyone for your reference. The details are as follows:

JavaScript is used here to generate a complex SQL query form. You will understand after running it. It can automatically modify your SQL statement according to the selected query conditions. It is a very typical application.

The screenshot of the running effect is as follows:

The specific code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>查询条件表单</title>
<style>
*{
 font-size:12px;
 padding:0;
 margin:0;
}
body{
 padding:40px;
}
#MainBox{
 border:#666 1px solid;
 background-color:#eee;
 width:700px;
}
#MainBox td{
 padding:4px;
}
#ConditionBox{
 height:150px;
 width:100%;
 overflow-y:auto;
 border:#bbb 1px solid;
 padding:2px;
 background-color:#fff;
}
.tmFrame{
 border:#eee 1px solid;
 padding:2px;
 width:100%;
}
.tmFrame_highlight{
 border:#666 1px solid;
 padding:2px;
 width:100%;
 background-color:#f7f7f7;
}
.fname{
 float:left;
 width:200px;
}
.conn{
 float:left;
 width:100px;
}
.fvalue{
 float:left;
 width:100px;
}
.handlebox{
 float:right;
 width:180px;
 display:none;
}
.handlebox_view{
 float:right;
 width:180px;
 display:block;
}
.rbox{
 float:right;
 margin:1px;
 background-color:#999;
 color:#fff;
 padding:1px;
 width:15px;
 cursor:hand;
}
legend{
 border:#bbb 1px solid;
 padding:4px;
}
fieldset{
 border:#bbb 1px solid;
 padding:4px;
}
.sqlwords{
 margin:2px;
 border:#bbb 1px solid;
 width:100%;
}
</style>
<script>
////构造函数
function ce(e){return document.createElement(e)}
/* Example:
* var a = cex("DIV", {onmouseover:foo, name:'div1', id:'main'});
*/
function cex(e, x){
 var a = ce(e);
 for (prop in x){
  a[prop] = x[prop];
 }
 return a;
}
/*
* function ge
* Shorthand function for document.getElementById(i)
*/
function ge(i){return document.getElementById(i)}
/*
* function ac
* Example: ac( house, ac(roof, shingles), ac(floor, ac(tiles, grout)))
*/
function ac(){
 if (ac.arguments.length > 1){
  var a = ac.arguments[0];
  for (i=1; i<ac.arguments.length; i++){
   if (arguments[i])
    a.appendChild(ac.arguments[i]);
  }
  return a;
 } else {
  return null;
 }
}
/////ID增量
function guid(){
 if (!window.__id) window.__id = 0;
 return ++window.__id;
}
//======建立条件类
function term(tname,fname,conn,fvalue,ttype){
 this.tname=tname;
 this.fname=fname;
 this.conn=conn;
 this.fvalue=fvalue;
 this.id= guid();
 this.ttype=ttype;
}
term.prototype.getHTML = function(){
 var termFrame = cex("DIV", {
  id:this.id,
  className:'tmframe',
  onmouseover:this.fc_term_onmouseover(),
  onmouseout:this.fc_term_onmouseout()
  });
 //var module = cex("DIV", {
  //id:'module'+this.id,
  //className:'module'
  //});
 var tttt=this.tname+"."+this.fname;
 if(this.ttype!='fset')
  tttt=this.tname;
 var mtt = cex("input", {
  id:'tp'+this.id,
  name:'fname'+this.id,
  type:"hidden",
  value:this.ttype
  });
 var fname = cex("DIV", {
  id:'fname'+this.id,
  className:'fname',
  innerHTML:tttt
  });
 var conn = cex("DIV", {
  id:'conn'+this.id,
  className:'conn',
  innerHTML:this.conn
  });
 var fvalue = cex("DIV", {
  id:'fvalue'+this.id,
  className:'fvalue',
  innerHTML:this.fvalue
  });
 var handlebox = cex("div", {
  id:'handlebox'+this.id,
  className:"handlebox"
  });
 var mdel = cex("div", {
  id:'tmdel'+this.id,
  onclick:this.fc_mdel_onclick(),
  className:"rbox",
  title:"删除此条件",
  innerHTML: 'X'
  });
 var mup = cex("div", {
  id:'tmup'+this.id,
  onclick:this.fc_mup_onclick(),
  className:"rbox",
  title:"向上移动",
  innerHTML: '↑'
  });
 var mdown = cex("div", {
  id:'tmdown'+this.id,
  onclick:this.fc_mdown_onclick(),
  className:"rbox",
  title:"向下移动",
  innerHTML: '↓'
  });
 var mzkh = cex("div", {
  id:'tzkh'+this.id,
  onclick:this.fc_mzkh_onclick(),
  className:"rbox",
  title:"添加左括号",
  innerHTML: '('
  });
 var mykh = cex("div", {
  id:'tykh'+this.id,
  onclick:this.fc_mykh_onclick(),
  className:"rbox",
  title:"添加右括号",
  innerHTML: ')'
  });
 var mand = cex("div", {
  id:'tand'+this.id,
  onclick:this.fc_mand_onclick(),
  className:"rbox",
  title:"添加并条件",
  innerHTML: 'and'
  });
 var mor = cex("div", {
  id:'tor'+this.id,
  onclick:this.fc_mor_onclick(),
  className:"rbox",
  title:"添加或条件",
  innerHTML: 'or'
  });
 // Build DIV
 ac (termFrame,
   mtt,
   ac (handlebox,
   mdel,
   mup,
   mdown,
   mykh,
   mzkh,
   mand,
   mor
   ),
   fname,
   conn,
   fvalue
  );
 return termFrame;
}
term.prototype.highlight = function(){
 ge("handlebox"+this.id).className = 'handlebox_view'; 
 ge(this.id).className = 'tmFrame_highlight';
}
term.prototype.lowlight = function(){
 ge("handlebox"+this.id).className = 'handlebox';
 ge(this.id).className = 'tmFrame';
}
term.prototype.remove = function(){
 var _this = ge(this.id);
 _this.parentNode.removeChild(_this);
}
term.prototype.moveup = function(){
 var _this = ge(this.id);
 var pre_this = _this.previousSibling;
 if(pre_this!=null){
  _this.parentNode.insertBefore(_this,pre_this);
  this.lowlight();
 }
}
term.prototype.movedown = function(){
 var _this = ge(this.id);
 var next_this = _this.nextSibling;
 if(next_this!=null){
  _this.parentNode.insertBefore(next_this,_this);
  this.lowlight();
 }
}
term.prototype.addzkh = function(){
 var _this = ge(this.id);
 var tzkh = new term('╭----------------','','','','zkh');
 var node_zkh = tzkh.getHTML();
 _this.parentNode.insertBefore(node_zkh,_this);
}
term.prototype.addykh = function(){
 var _this = ge(this.id);
 var tykh = new term('╰----------------','','','','ykh');
 var node_ykh = tykh.getHTML();
 if(_this.nextSibling!=null)
  _this.parentNode.insertBefore(node_ykh,_this.nextSibling);
 else
  _this.parentNode.appendChild(node_ykh);
}
term.prototype.addand = function(){
 var _this = ge(this.id);
 var tand = new term(' 并且','','','','tand');
 var node_and = tand.getHTML();
 if(_this.nextSibling!=null)
  _this.parentNode.insertBefore(node_and,_this.nextSibling);
 else
  _this.parentNode.appendChild(node_and);
}
term.prototype.addor = function(){
 var _this = ge(this.id);
 var tor = new term(' 或者','','','','tor');
 var node_or = tor.getHTML();
 if(_this.nextSibling!=null)
  _this.parentNode.insertBefore(node_or,_this.nextSibling);
 else
  _this.parentNode.appendChild(node_or);
}
///对象控制函数
term.prototype.fc_term_onmouseover = function(){
 var _this = this;
 return function(){
  //if (!_this.isDragging)
   _this.highlight();
 }
}
term.prototype.fc_term_onmouseout = function(){
 var _this = this;
 return function(){
  //if (!_this.isDragging)
   _this.lowlight();
 }
}
term.prototype.fc_mdel_onclick = function(){
 var _this = this;
 return function(){
  _this.remove();
 }
}
term.prototype.fc_mup_onclick = function(){
 var _this = this;
 return function(){
  _this.moveup();
 }
}
term.prototype.fc_mdown_onclick = function(){
 var _this = this;
 return function(){
  _this.movedown();
 }
}
term.prototype.fc_mzkh_onclick = function(){
 var _this = this;
 return function(){
  _this.addzkh();
 }
}
term.prototype.fc_mykh_onclick = function(){
 var _this = this;
 return function(){
  _this.addykh();
 }
}
term.prototype.fc_mand_onclick = function(){
 var _this = this;
 return function(){
  _this.addand();
 }
}
term.prototype.fc_mor_onclick = function(){
 var _this = this;
 return function(){
  _this.addor();
 }
}
/////插入页面
function insertterm(){
 var tname = document.all.tname.value;
 var fname = document.all.fname.value;
 var conn = document.all.conn.value;
 var fvalue = document.all.fvalue.value;
 //xl(tname+"|"+fname+"|"+conn+"|"+fvalue);
 var tm = new term(tname,fname,conn,fvalue,"fset");
 var tmHTML = tm.getHTML();
 ac(ge("ConditionBox"),tmHTML);
 //ZA.addterm(tm);
 addtofrom(tname);
}
var tt = new Array();
function addtofrom(tname){
  var ttexit="no";
  for(var i=0;i<tt.length;i++){
   if(tt[i]==tname)
    ttexit="yes";     
  }
  if(ttexit=="no"){
   tt[i]=tname;
   //alert(tt[i]);
  }
}
//====条件控制窗口函数
function CBadd(){
 var h = document.all.ConditionBox.offsetHeight;
 document.all.ConditionBox.style.height = h + 20 + "px";
}
function CBcut(){
 var h = document.all.ConditionBox.offsetHeight;
 if(h>=150)
  document.all.ConditionBox.style.height = h - 20 + "px";
 else
  return false;
}
function getSQL(){
 var sql="";
 var ma = ge("ConditionBox").childNodes;
 for(i=0;i<ma.length;i++){
  var id = ma[i].getAttribute("id");
  var tp = ge("tp"+id).value;
  if(tp=="fset"){
   //sql+=" "+ge("fname"+id).innerHTML;
   //sql+=" "+ge("conn"+id).innerHTML;
   //sql+=" \""+ge("fvalue"+id).innerHTML+"\"";
   var fname=ge("fname"+id).innerHTML;
   var conn=ge("conn"+id).innerHTML;
   var fvalue=ge("fvalue"+id).innerHTML;
   sql+=" "+fname;
   if(conn=="等于")
    sql+=" = "+"\'"+fvalue+"\'";
   if(conn=="大于")
    sql+=" > "+"\'"+fvalue+"\'";
   if(conn=="小于")
    sql+=" < "+"\'"+fvalue+"\'";
   if(conn=="不等于")
    sql+=" <> "+"\'"+fvalue+"\'";
   if(conn=="为空")
    sql+=" is null ";
   if(conn=="不为空")
    sql+=" is not null ";
   if(conn=="包含")
    sql+=" like \'%"+fvalue+"%\'";
  }
  else{
   //sql+=" "+ge("fname"+id).innerHTML;
   if(tp=="zkh")
    sql+=" (";
   if(tp=="ykh")
    sql+=" )";
   if(tp=="tand")
    sql+=" and";
   if(tp=="tor")
    sql+=" or";
  }
  //var mn = ma.childNodes;
 }
 var ffrom = "FROM "+getFrom();
 ge("sqlwords").value ="Select * "+ ffrom+" Where "+sql;
}
function getFrom(){
 var ff=tt.toString();
 return ff;
}
</script>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0" id="MainBox">
 <tr> 
 <td colspan="2" style="background-color:#999;color:#000;font-weight:bolder;font-size:14px">复杂查询表单</td>
 </tr>
 <tr> 
 <td><div id="ConditionBox"></div>
 <div style="width:100%"><SPAN title='放大显示框' style='float:right;FONT-SIZE: 14px; CURSOR: hand;FONT-FAMILY: webdings' onclick='CBadd()'>6</SPAN><SPAN title='缩小显示' style='float:right;FONT-SIZE: 14px; CURSOR: hand;FONT-FAMILY: webdings' onclick='CBcut()'>5</SPAN></div></td>
 </tr>
 <tr> 
 <td>
 <fieldset>
 <legend>SQL表达式</legend>
  <input type="text" id="sqlwords" class="sqlwords" /><input type="submit" name="Submit" value="GET SQL" onclick="getSQL()" style="float:right"/>
  </fieldset>
  </td>
 </tr>
 <tr> 
 <td>
 <fieldset>
 <legend>定义条件</legend>
 <table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
   <td>表</td>
   <td><select name="tname" id="tname">
    <option value="table1" selected="selected">表1</option>
    <option value="table2">表2</option>
    <option value="table3">表3</option>
    <option value="table4">表4</option>
    <option value="table5">表5</option>
   </select></td>
   <td>字段</td>
   <td><select name="fname" id="fname">
    <option value="f1">字段1</option>
    <option value="f2">字段2</option>
    <option value="f3">字段3</option>
    <option value="f4">字段4</option>
    <option value="f5">字段5</option>
    <option value="f6">字段6</option>
    <option value="f7">字段7</option>
   </select></td>
   <td>关系</td>
   <td><select name="conn" id="conn">
    <option value="大于">大于</option>
    <option value="等于">等于</option>
    <option value="小于">小于</option>
    <option value="不等于">不等于</option>
    <option value="为空">为空</option>
    <option value="不为空">不为空</option>
    <option value="包含">包含</option>
   </select></td>
   <td>值</td>
   <td><input name="fvalue" type="text" id="fvalue" value="111111" /></td>
   <td><input type="submit" name="Submit" value="增加新条件" onclick="insertterm()"/></td>
  </tr>
  </table>
  </fieldset>
  </td>
 </tr>
</table>
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools