Home > Web Front-end > Layui Tutorial > How do I create and style forms using Layui?

How do I create and style forms using Layui?

Karen Carpenter
Release: 2025-03-12 13:32:16
Original
555 people have browsed it

Creating and Styling Forms with Layui

Layui offers a streamlined approach to form creation, leveraging its intuitive syntax and pre-built components. To create a basic form, you'll primarily use the <form></form> element along with Layui's form elements like <input>, <select></select>, <textarea></textarea>, <checkbox></checkbox>, and <radio></radio>. Crucially, you need to assign the lay-filter attribute to your form. This attribute is essential for Layui to recognize and manage the form's data. For example:

<form class="layui-form" lay-filter="myForm">
  <div class="layui-form-item">
    <label class="layui-form-label">Username:</label>
    <div class="layui-input-block">
      <input type="text" name="username" lay-verify="required" placeholder="Enter your username" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">Password:</label>
    <div class="layui-input-block">
      <input type="password" name="password" lay-verify="required|password" placeholder="Enter your password" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="submitBtn">Submit</button>
    </div>
  </div>
</form>
Copy after login

This code snippet demonstrates a simple form with username and password fields. lay-verify adds validation rules (required, password in this case). lay-submit and lay-filter on the button trigger form submission and specify the filter for handling the submission. Remember to include the necessary Layui CSS and JavaScript files in your HTML. Styling is further enhanced through Layui's CSS classes, allowing for consistent and visually appealing forms. You can adjust spacing, sizes, and other visual aspects using standard CSS techniques within the provided classes.

Common Pitfalls to Avoid When Building Forms with Layui

Several common issues can arise when working with Layui forms. One frequent problem is neglecting the lay-filter attribute on the form itself. Without it, Layui's form module won't function correctly. Another pitfall is improper use of validation rules (lay-verify). Incorrectly specifying rules or forgetting to include them can lead to unexpected behavior or lack of validation. Overlooking the correct usage of lay-submit and lay-filter on the submit button can also prevent the form from submitting data correctly. Finally, forgetting to initialize Layui's form module using layui.form.render() after dynamically adding form elements can result in the elements not being recognized or styled correctly. Always ensure that you correctly initialize the form module after any DOM manipulation involving form elements. Thorough testing and careful attention to these details will prevent common headaches.

Integrating Layui Forms with Existing Backend Systems

Integrating Layui forms with your backend system involves handling form submission and data processing. The most common method is using AJAX to send form data to your backend API. Layui's form module simplifies this process. When the form is submitted, you can use JavaScript's $.ajax (or a similar method like fetch) to send the form data. You'll need to obtain the form data using layui.form.val('myForm') (replacing 'myForm' with your form's lay-filter value). This returns a JavaScript object containing the form data.

layui.form.on('submit(submitBtn)', function(data){
  var formData = data.field; // Get form data
  $.ajax({
    url: '/your-backend-endpoint',
    type: 'POST',
    data: formData,
    success: function(response) {
      // Handle successful submission
      console.log(response);
    },
    error: function(error) {
      // Handle errors
      console.error(error);
    }
  });
  return false; // Prevent default form submission
});
Copy after login

This code snippet shows how to handle form submission using AJAX. Replace /your-backend-endpoint with your backend API endpoint. Your backend should then process the received data accordingly. Remember to adjust the data format (e.g., JSON) to match your backend API's requirements.

Customizing the Default Styling of Layui Forms

Layui provides a foundation for styling, but you can easily customize it to match your website's theme. The primary approach is to override Layui's default CSS using your own custom CSS. You can achieve this by creating a separate CSS file and including it after the Layui CSS file. In your custom CSS, target the specific Layui CSS classes used in forms (e.g., .layui-form, .layui-form-item, .layui-input, .layui-btn) and modify their properties (colors, fonts, sizes, etc.). For example:

.layui-form-item {
  margin-bottom: 20px; /* Adjust margin */
}

.layui-input {
  border-color: #ccc; /* Change border color */
}

.layui-btn {
  background-color: #007bff; /* Change button color */
  color: white;
}
Copy after login

This code snippet demonstrates basic CSS overrides. You can adjust any aspect of the form's appearance using standard CSS techniques. Remember to be mindful of CSS specificity when overriding styles to ensure your custom styles take precedence. Consider using a CSS preprocessor like Sass or Less for more organized and maintainable custom CSS. Using the browser's developer tools can help you inspect the existing CSS classes and identify the properties you need to modify.

The above is the detailed content of How do I create and style forms using Layui?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template