Commonly used form code sharing in JavaScript (Collection)
Mobile phone (text box):
<input type="text" name="" maxlength="11" placeholder="" autocomplete="off">
Basic form validation
<script>$(function(){ $('.fr-form').submit(function(event){ event.preventDefault();//阻止表单提交事件 $(this).find('.error-tip').html(''); var name = $('.username'); var mobile = $('.mobile'); var regTest = /^1[3|4|5|7|8][0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/; if(!name.val().length || name.val() == name.attr('data-value') ){alert('请填写姓名');return false;} if(!mobile.val().length || mobile.val() == mobile.attr('data-value') ){alert('请填写电话');return false;} if(!regTest.test( mobile.val() )){alert('电话格式不对');return false;} $.ajax({ url:'/signup', type:'POST', data:'realname='+name+'&mobile='+mobile+'&source=39', dataType:'json', success:function(data){ if(data.status == 1){ alert(data.msg); }else{ alert('提交成功'); } } }) return false; }); }); </script> <form method="post" action="" class="fr-form"> <input type="text" class="input username" data-value="您的称呼" value=""> <input type="text" class="input mobile" data-value="您的电话" value=""> <p class="error-tip"></p><input type="submit" class="frformbtn" value="免费申请"> </form>
checkbox (checkbox) value
<script src=" </script> <script type="text/javascript">$(function(){ $("#form").submit(function(){//表单提交:复选框取值 //var checkboxs = $('input[type="checkbox"]:checked'); var checkboxs = $('input[type="checkbox"][name="test"]:checked'); var checkboxs = $('input:checkbox[name="test"]:checked'); console.log("长度: "+checkboxs.length); checkboxs.each(function(){ var s=$(this).val(); console.log(s); }); console.log("------------"); var checkboxs=$('input:checkbox[name="test"]:checked'); for(i=0;i<checkboxs.length;i++){ console.log( $(checkboxs[i]).val()); } return false; }); });</script><form method="post" action="" id="form"> <input type="checkbox" name="test" value="1"> <input type="checkbox" name="test" value="2"> <input type="checkbox" name="test" value="3"> <input type="checkbox" name="test" value="4"> <input type="checkbox" name="test" value="5"> <input type="submit"> <input type="reset"></form>
radio (radio button) value
<script src=" </script> <script type="text/javascript">$(function(){ $("#form").submit(function(){//表单提交:单选框取值 var aaa=$('input:radio[name="aaa"]:checked').val(); alert(aaa); return false; }); });</script><form method="post" action="" id="form"> <input type="radio" name="aaa" value="1" checked> <input type="radio" name="aaa" value="2"> <input type="radio" name="aaa" value="3"> <input type="submit"></form>
checkbox select all (native js)
<script src=" </script> <script type="text/javascript">$(function(){ $("#check_all").click(function(){ var a=$(this)[0].checked; //alert( typeof a); var inputs = document.getElementsByTagName("input"); for(var i=0; i< inputs.length; i++){ if(inputs[i].type == "checkbox"){ inputs[i].checked = a; } } }); }); </script> <input type="checkbox" name="" id="check_all">选择所有<hr> <input type="checkbox" name=""> <br> <input type="checkbox" name=""> <br> <input type="checkbox" name=""> <br> <input type="checkbox" name=""> <br>
checkbox Select all (jquery)
<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ $("#check_all").click(function(){ if($(this).is(":checked")){ $("input[name=aa]").prop("checked", true); }else{ $("input[name=aa]").prop("checked", false); } }); }); </script> <input type="checkbox" name="" id="check_all">选择所有<hr> <input type="checkbox" name="aa"> <br> <input type="checkbox" name="aa"> <br> <input type="checkbox" name="aa"> <br> <input type="checkbox" name="aa"> <br>
checkbox Check yourself and Check boxes for all subordinate subdirectories: .prop("checked",true); 2015-12-1
<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ $("input[type=checkbox]").click(function(){ var s=$(this)[0].checked; $(this).parent().find("input[type=checkbox]").prop("checked",s); }); });</script><ul> <li><input type="checkbox" name=""> <ul> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""> <ul> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""></li> </ul> </li> </ul> </li> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""> <ul> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""></li> <li><input type="checkbox" name=""></li> </ul> </li></ul>
A common effect of the text box:
When it is in the "focus" state, it is dark text. After the mouse is moved away, the text changes to light color.
When the text box is not filled in (or empty), a prompt message is displayed. After it has been filled in, the text color becomes darker and the prompt message is removed.
<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ $(".input").blur(function(){ var _defalut = $(this)[0].defaultValue; var _value = $(this).val(); if(_value==_defalut || _value ==""){ $(this).val(_defalut); $(this).removeClass("cGray"); }else{ $(this).addClass("cGray"); } }); $(".user-container .input").focus(function(){ var _defalut = $(this)[0].defaultValue; var _value = $(this).val(); if(_value==_defalut){ $(this).val(""); } }); }); </script> <ul> <li> <input type="text" name="" class="input" value="手机号码 (填写手机号)"> </li> <li> <input type="text" name="" class="input" value="密码 (6-16位数字、字母)"> </li> </ul>
textarea:
Multi-line text box form validation: 2016-5-3
<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ //表单提交(实际是表单不提交,发ajax) $('.questions-form').submit(function() { event.preventDefault();//阻止表单提交事件 var _textarea = $('.questions-form').find('textarea'); var _str = $.trim(_textarea.val()); var _len = _str.replace(/[^\x00-\xff]/g, '__').length; if (_textarea.attr('data-value') == _str) {alert('请填写内容');return false;} if (_len < 10) {alert('内容过短,长度应在10-500个字之间');return false;} if (_len > 500) {alert('内容超长了,长度在10-500个字之间,现在已 ' + _len + ' 个英文字符长度');return false;} //ajax.. return false; }); });</script> <form method="post" class="questions-form"> <textarea name="" rows="6" cols="50"></textarea> <input type="submit" value="提交" class=""></form>
Calculate the character length of the text box (1 Chinese character counts as 2 English characters) 2016-1-15
<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ $("#textarea").blur(function(){ var strLen = $(this).val().replace(/[^\x00-\xff]/g,'__').length; alert(strLen); }); });</script> <textarea id="textarea" rows="5" cols="66"> </textarea>
Restrict text box Only numbers are allowed to be entered: utinguishes for 6-6-6
##<script type="text/javascript" src=" </script> <script type="text/javascript">$(function(){ //房屋结构: 室、厅、卫、厨房、阳台(限制只允许输入数字) $(".ipt2").keyup(function(){ var _val = $(this).val(); //var _val = _val.replace(/[^\-?\d.]/g,'') //限制文本框只能输入正数,负数,小数 //var _val = _val.replace(/[^\d.]/g,'') //限制文本框只能输入正数,小数 var _val = _val.replace(/\D/g,'') //限制文本框只能输入数字 $(this).val(_val); }); </script> <input type="text" name="shi" value="2" autocomplete="off" maxlength="10" class="ipt2">
<select> <optgroup label="Sirs"> <option value ="aaa">aaa</option> <option value ="bbb">bbb</option> </optgroup> <optgroup label="Cars"> <option value ="xxx">xxx</option> <option value ="yyy">yyy</option> </optgroup></select>
Text box (drop-down prompt):
##<input id="myCar" list="cars" /><datalist id="cars">
<option value="BMW">
<option value="Ford">
<option value="Volvo"></datalist>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script><script type="text/javascript">$(function(){ $("input[type=text]").dblclick(function(){ /*双击后将placeholder的值设为当前值*/ if( $(this).val().length==0){ $(this).val($(this).attr('placeholder')); } }); });</script><input type="text" value="" placeholder="hidden">
confirm:
<script type="text/javascript">$(function(){
$("#list_form").submit(function(){//表单提交:
if ( confirm("确定删除已选中的信息吗?") ){
return true;
}else{ return false;
}
});
});</script>
Serialized form value:
##
<script type="text/javascript">$(function(){ $("form").submit(function(){ event.preventDefault();//阻止表单提交事件 var s=$('form').serialize();//序列化表单值 alert(s); }); });</script><form method="post" action=""> <input type="text" name="uname" value="aaa"> <input type="text" name="city" value="beijing"> <input type="submit" value="" class=""></form>
JSON object < == > JSON string, mutual conversion:
Note: ie8 (compatibility mode), ie7 and ie6 do not have JSON objects. It is recommended to use the official JSON method and introduce json.js .
var s1={a:1,b:2,c:333}var s2=JSON.stringify(s1); //将json对象转为字符串var s3=JSON.parse(s2); //将json字符串转为json对象
Upload button (change traditional appearance) [Important]
2016-6-3 changes
<!-- 上传按钮(改变传统上传按钮外观) --> <style type="text/css"> .filebtn-box {position:relative;width:120px;height:120px;overflow:hidden;} /* 总容器 */ .filebtn-hide{position:absolute;left:0;top:0;right:0;bottom:0;width:100%;height:100%;margin:0;padding:0;z-index:2; font-size:1000px;opacity:0;filter:alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";} /* 放在上层的透明的上传控件 */ .filebtn-img{position:absolute;left:0;top:0;right:0;bottom:0;width:100%;height:100%;z-index:1;} /* 用图片替代上传控件 */ .filebtn-ipt{position:absolute;left:0;top:0;right:0;bottom:0;width:100%;height:100%;z-index:1; border:1px solid #ccc;background:#f8f8f8;color:#666;text-align:center;font-size:14px;font-weight:bold;border-radius:4px;} /* 用按钮替代上传控件 */ </style> <p class="filebtn-box"> <input type="file" name="uploadimg" class="filebtn-hide"> <img src="http://pic.58pic.com/58pic/14/73/88/32x58PICwrz_1024.jpg" class="filebtn-img"></p><hr><p class="filebtn-box"> <input type="file" name="uploadimg" class="filebtn-hide"> <input type="button" name="" class="filebtn-ipt" value="本地上传"></p>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ //房屋类型(弹出层) $(".js-housetype-btn").click(function(){ $('.housetype-dropbox .absbox').slideToggle(200); }); $(".housetype-dropbox .housetype-option").click(function(){ $(this).addClass('active').siblings().removeClass('active'); $('.js-housetype-btn').find('.ipt').val($(this).html()); $('.housetype-dropbox .absbox').slideUp(500); }); }); </script> <style type="text/css"> ul,li{margin:0;padding:0;list-style:none;} dl,dt,dd,p{margin:0;padding:0;} .l{float:left;} .ipt-line{width:310px;height:42px;padding:0 25px;font-size:14px;line-height:42px;} .ipt-line > dt{position:relative;float:left;color:#333;width:68px;height:42px;font-weight:bold;} .ipt-line > dd{position:relative;float:left;color:#999;width:240px;height:42px;} .ipt-line .ipt{display:block;color:#999;line-height:42px;height:42px;border:none;} .ipt-line .js-area-btn{width:240px;height:42px;cursor:pointer;} .js-housetype-btn .ipt{width:5em;} .js-housetype-btn .housetype-icon{margin-top:20px;} .housetype-dropbox{position:relative;height:0;}/* 房屋类型选择面板 */ .housetype-dropbox .absbox{position:absolute;display:none;left:0;top:0;width:323px;padding:14px 0 0 35px;background:#fff;border:1px solid #ececec;box-shadow:0 2px 10px #ccc;z-index:1;} .housetype-dropbox .absbox .housetype-option{float:left;width:86px;height:28px;line-height:28px;background:#f1f1f1;color:#666;margin:0 10px 12px 0;text-align:center;cursor:pointer;} .housetype-dropbox .absbox .housetype-option.active{background:#eb5405;color:#fff;} </style> <dl class="ipt-line clearfix"> <dt class="l">类型</dt> <dd class="l js-housetype-btn"><input type="text" name="housetype" value="普通住宅" class="ipt l" disabled></dd> </dl> <!-- 下拉选择面板 start --> <div class="housetype-dropbox"> <ul class="absbox"> <li class="housetype-option active">普通住宅</li> <li class="housetype-option">别墅</li> <li class="housetype-option">公寓</li> <li class="housetype-option">小户型</li> </ul> </div> <!-- 下拉选择面板 end -->
Determine whether to hide:
(Put a copy of the code here for easy search.)
var s1={a:1,b:2,c:333} var s2=JSON.stringify(s1); //将json对象转为字符串 var s3=JSON.parse(s2); //将json字符串转为json对象
The above is the detailed content of Commonly used form code sharing in JavaScript (Collection). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
