Table of Contents
Avoid submitting the form multiple times
Modify the background color of the text box according to conditions
Get the selected text
Selected part Text
Get clipboard information
Automatically switch focus
Home Web Front-end JS Tutorial Practical tips about form scripts in JavaScript

Practical tips about form scripts in JavaScript

Oct 17, 2017 am 09:25 AM
javascript js Practical Tips


Avoid submitting the form multiple times

var form = document.getElementById("myform");

form.addEventListener("submit", function(event) {    
var event = event || window.event;    
var target = event.target;    
var btn = target.elements["submit-btn"];
    btn.disabled = true;
}, false);
Copy after login

The above code adds an event handler for the submit event of the form. After the event is triggered, the code gets the submit button and puts it Its disabled attribute is set to true. Note that this function cannot be implemented through the onclick event handler. The reason is due to the "time difference" between different browsers: some browsers will trigger the click event before triggering the submit event of the form.


Modify the background color of the text box according to conditions

var textbox = document.forms[0].elements[0];

textbox.addEventListener("focus", function(event) {    var event = event || window.event,
        target = event.target;    if (target.style.backgroundColor != "red") {
        target.style.backgroundColor = "yellow";
    }
}, false);

textbox.addEventListener("blur", function(event) {    var event = event || window.event,
        target = event.target;    if (/[^\d]/.test(target.value)) {
        target.style.backgroundColor = "red";
    } else {
        target.style.backgroundColor = "";
    }
}, false);

textbox.addEventListener("change", function(event) {    var event = event || window.event,
        target = event.target;
    console.log(123)    if (/[^\d]/.test(target.value)) {
        target.style.backgroundColor = "red";
    } else {
        target.style.backgroundColor = "";
    }
}, false)
Copy after login

Get the selected text

function getSelectedText(textbox) {
    if (typeof textbox.selectionStart == "number") {        
    return textbox.value.substring(textbox.selectionStart, textbox.sectionEnd);
    } else if (document.selection) {//兼容IE
        return document.selection.createRange().text;
    }
}
Copy after login

Practical tips about form scripts in JavaScript


Selected part Text

function selecText(textbox, startIndex, stopIndex) {    
if (textbox.setSelectionRange) {
        textbox.setSelectionRange(startIndex, stopIndex);
    } else if (textbox.createTextRange) {//兼容IE8及更早版本
        var range = textbox.createTextRange();        
        range.collapse(true);        
        range.moveStart("character", startIndex);        
        range.moveEnd("character", stopIndex - startIndex);        
        range.select();
        textbox.focus();
    }
}
Copy after login

Test 1:

textbox.addEventListener("focus", function(event) {    var event = event || window.event,
        target = event.target;    if (target.style.backgroundColor != "red") {
        target.style.backgroundColor = "yellow";
    }
    selecText(textbox, 0, 1);
}, false);
Copy after login

Effect:
Practical tips about form scripts in JavaScript

Test 2:

selecText(textbox, 0, 5);
Copy after login

Practical tips about form scripts in JavaScript


Get clipboard information

    getClipboardText: function(event) { //获得剪切板内容
        var clipboardData = (event.clipboardData || window.clipboardData);        
        return clipboardData.getData("text");
    }

    setClipboardText: function(event, value) { //设置剪切版内容
        if (event.clipboardData) {            
        return event.clipboardData.setData("text/plain", value);
        } else if (window.clipboardData) {            
        return window.clipboardData.setData("text", value);
        }
    }
Copy after login

Note: Firefox, Safari, Chrome only allow access to the getData() method in the onpaste event handler. (Test 2017/9/1: in copy Get the empty string under the event)

Purpose:
In the paste event, you can determine whether the value of the clipboard is valid. If it is invalid, you can cancel the default as in the example below Behavior.

textbox.addEventListener("paste", function(event) {
    var event = event || window.event;    
    text = getClipboardText(event);    
    if (!/^\d*$/.test(text)) {        
    event.preventDefault();
    }
}, false)
Copy after login

Automatically switch focus

Effect:
Practical tips about form scripts in JavaScript

//HTML
 <form method="post" id="myform">
        <input type="text" name="tel1" id="textTel1" maxlength="3">
        <input type="text" name="tel2" id="textTel2" maxlength="3">
        <input type="text" name="tel3" id="textTel3" maxlength="4">
    </form>
Copy after login
//Js
(function() {
    function tabForward(event) {
        var event = event || window.event;
        target = event.target;

        if (target.value.length == target.maxLength) {
            var form = target.form;

            for (var i = 0, len = form.elements.length; i < len; i++) {
                if (form.elements[i] == target) {
                    if (form.elements[i + 1]) {
                        form.elements[i + 1].focus();
                    }
                }
            }
        }
    }

    var textbox1 = document.getElementById("textTel1");
    var textbox2 = document.getElementById("textTel2");
    var textbox3 = document.getElementById("textTel3");

    textbox1.addEventListener("keyup", tabForward);
    textbox2.addEventListener("keyup", tabForward);
    textbox3.addEventListener("keyup", tabForward);})();
Copy after login

The above is the detailed content of Practical tips about form scripts in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Troubleshooting Tomcat 404 Errors: Quick and Practical Tips Troubleshooting Tomcat 404 Errors: Quick and Practical Tips Dec 28, 2023 am 08:05 AM

Practical Tips to Quickly Solve Tomcat404 Errors Tomcat is a commonly used JavaWeb application server and is often used when developing and deploying JavaWeb applications. However, sometimes we may encounter a 404 error from Tomcat, which means that Tomcat cannot find the requested resource. This error can be caused by multiple factors, but in this article, we will cover some common solutions and tips to help you resolve Tomcat 404 errors quickly. Check URL path

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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

Practical tips for efficiently solving Java large file reading exceptions Practical tips for efficiently solving Java large file reading exceptions Feb 21, 2024 am 10:54 AM

Practical tips for efficiently resolving large file read exceptions in Java require specific code examples. Overview: When processing large files, Java may face problems such as memory overflow and performance degradation. This article will introduce several practical techniques to effectively solve Java large file reading exceptions, and provide specific code examples. Background: When processing large files, we may need to read the file contents into memory for processing, such as searching, analyzing, extracting and other operations. However, when the file is large, the following problems are often encountered: Memory overflow: trying to copy the entire file at once

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

See all articles