Home Web Front-end JS Tutorial Use JavaScript to implement custom styles and prompts for forms

Use JavaScript to implement custom styles and prompts for forms

Jun 15, 2023 pm 02:41 PM
javascript form style Prompt message

With the popularity of web applications, forms have become an indispensable part of our daily work. When we use a form, we usually need to enter some basic information to submit to the backend for processing. However, traditional forms have some shortcomings, whether in terms of aesthetics or operational friendliness. Therefore, in this article, we will focus on how to use JavaScript to implement custom styles and prompts for forms.

1. Implement style customization of the form

To achieve style customization of the form, we first need to understand the basic structure and attributes of HTML form elements. In web pages, we usually use the form tag to define a form, and then add various form elements in the form tag, such as input, select, textarea, etc. Then, for these form elements, we can use CSS to style them. However, if we want to implement more complex custom styles, we need to use JavaScript to operate it.

  1. Add a class name to the form element

Before implementing the form element style customization, we need to add a class name to the form element first. In HTML, we can use the class attribute to add one or more class names to an element, for example:

<input type="text" class="my-input">
Copy after login

In CSS, we can use the class selector to select a certain class name, for example:

.my-input {
  width: 200px;
  height: 30px;
  border: 1px solid #ccc;
}
Copy after login

In this way, we can set some basic styles for the form elements.

  1. Add status to form elements

In addition to basic styles, form elements also have some special states that need to be processed, such as: focus, out of focus, mouse passing, etc. . In order to implement these styles, we need to use JavaScript to manipulate the state of form elements.

const myInput = document.querySelector('.my-input');

myInput.addEventListener('focus', function() {
  // 当元素聚焦时需要执行的操作
  myInput.style.border = "1px solid blue";
});

myInput.addEventListener('blur', function() {
  // 当元素失焦时需要执行的操作
  myInput.style.border = "1px solid #ccc";
});

myInput.addEventListener('mouseenter', function() {
  // 当鼠标经过元素时需要执行的操作
  myInput.style.backgroundColor = "#f5f5f5";
});

myInput.addEventListener('mouseleave', function() {
  // 当鼠标离开元素时需要执行的操作
  myInput.style.backgroundColor = "#fff";
});
Copy after login

In this way, we can add styles in various states to the form elements.

  1. Realize linkage effects of form elements

In the form, there are linkage effects between some form elements, for example: the options of the drop-down selection box depend on the previous level drop-down Select box options and more. To achieve this linkage effect, we also need to use JavaScript.

<select class="province">
  <option value="0">请选择省份</option>
  <option value="1">河北省</option>
  <option value="2">山东省</option>
  <option value="3">广东省</option>
</select>

<select class="city">
  <option value="0">请选择城市</option>
</select>
Copy after login
const provinceSelect = document.querySelector('.province');
const citySelect = document.querySelector('.city');

provinceSelect.addEventListener('change', function() {
  const provinceId = provinceSelect.value;
  // 根据省份获取对应的城市列表
  const cityList = getCityList(provinceId);
  // 清空城市下拉列表的选项
  citySelect.innerHTML = '<option value="0">请选择城市</option>';
  // 动态添加城市选项
  cityList.forEach(function(city) {
    const option = document.createElement('option');
    option.value = city.id;
    option.textContent = city.name;
    citySelect.appendChild(option);
  });
});

function getCityList(provinceId) {
  // 根据省份id获取对应的城市列表
  // ...
  return cityList;
}
Copy after login

In this way, we can achieve the linkage effect between form elements.

2. Implement data verification and prompts on the form

In addition to style customization, the form also needs data verification and prompts. When we fill in a form, we often need to provide different prompts based on different scenarios. For example: when the input box is empty, we need to prompt that it cannot be empty, the input content in the input box is in the wrong format, etc. Therefore, we need to add corresponding data verification and prompt functions to the form during the development process.

  1. Use regular expressions for data verification

When verifying form data, we usually need to use regular expressions for matching and verification. For example: to verify whether the mobile phone number format is correct, you can use the following code:

const phoneInput = document.querySelector('.phone-input');

phoneInput.addEventListener('blur', function() {
  const phone = phoneInput.value;
  if (!/^1d{10}$/.test(phone)) {
    alert('手机号码格式不正确');
  }
});
Copy after login

In this example, we use a regular expression to match 11 digits starting with 1. If the mobile phone number format is incorrect, a popup will appear. Prompt box prompts.

  1. Implement real-time verification and display prompts

In addition to regular expression verification, we can also implement real-time verification and display prompts. For example: to set the password box must contain uppercase and lowercase letters and numbers, you can use the following code:

<input type="password" class="password-input" placeholder="请输入密码">

<div class="password-tip">密码需要包含大小写字母和数字</div>
Copy after login
.password-tip {
  color: red;
  display: none;
}
Copy after login
const passwordInput = document.querySelector('.password-input');
const passwordTip = document.querySelector('.password-tip');

passwordInput.addEventListener('input', function() {
  const value = passwordInput.value;
  if (/d/.test(value) && /[a-z]/.test(value) && /[A-Z]/.test(value)) {
    passwordTip.style.display = 'none';
  } else {
    passwordTip.style.display = 'block';
  }
});
Copy after login

In this example, we need to verify that the content entered in the input box must contain uppercase and lowercase letters and numbers. In order to realize this function, we added an input event listener to the input box. When the user enters content in the input box, it will be verified in real time and a prompt will be displayed.

3. Summary

Through the introduction of this article, we have learned how to use JavaScript to implement custom styles and prompts for forms. In terms of form customization, using JavaScript can give us more flexible operating space and can realize various complex business needs. Therefore, having an in-depth understanding of JavaScript form customization and proficient use of it is of great significance to our web development work.

The above is the detailed content of Use JavaScript to implement custom styles and prompts for forms. 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 let all users print specified prompt information when logging in in Linux How to let all users print specified prompt information when logging in in Linux Feb 19, 2024 pm 05:12 PM

In Linux systems, through configuration files and scripts, you can display specified prompt information when all users log in. Next, we will introduce several commonly used implementation methods. Method 1: Modify the /etc/issue file. Open the terminal and use a text editor (such as vi or nano) to edit the /etc/issue file with root permissions. sudovi/etc/issue Add the prompt message you want to display at the end of the file, for example: Welcome to MyLinuxSystem! Please beaware that all activities are monitored. Save and close the file. Now when the user logs in, the system will display /

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles