Home Web Front-end Layui Tutorial How to set default selections in the layui radio box

How to set default selections in the layui radio box

May 16, 2025 am 11:21 AM
Browser layui layui radio box Selected by default

Setting the default selection of the radio box in Layui can be achieved by using the checked property of HTML to directly set the default selection. Dynamically set default selections with JavaScript and re-render the form using layui.form.render('radio'). This method not only improves the user experience, but also flexibly sets default values ​​based on back-end data, and is suitable for various dynamic scenarios.

How to set default selections in the layui radio box

Setting the default selection of radio boxes in Layui is a common requirement, especially in form development. So, how to implement this function gracefully? Let's take a deeper look.

As a front-end framework, Layui provides us with rich UI components, where radio boxes are an integral part of the form. Setting the default selection not only improves the user experience, but also simplifies user operations in certain scenarios. Next, I will share some practical methods and experiences.

The first thing to know is that Layui's radio box can be selected by default through checked property. Let's start with the most basic usage:

 <div class="layui-form-item">
  <div class="layui-input-block">
    <input type="radio" name="sex" value="male" title="male" checked>
    <input type="radio" name="sex" value="female" title="female">
  </div>
</div>

In this example, the checked property is added to the first radio box so that it will be selected when the page is loading. However, setting default values ​​by HTML attributes alone may not be flexible enough in some dynamic scenarios.

In actual development, we often need to dynamically set the default selection based on the data returned by the backend. At this time, the power of JavaScript is revealed. Suppose we get a user's gender information from the backend and want to set the default selection based on this information, we can do this:

 // Assume that the user gender information obtained from the backend var userSex = &#39;male&#39;;

// Use Layui&#39;s form module layui.use(&#39;form&#39;, function(){
  var form = layui.form;

  // Get all radio boxes var radios = document.getElementsByName(&#39;sex&#39;);

  // traverse the radio box, find the match and set it to select for (var i = 0; i < radios.length; i ) {
    if (radios[i].value === userSex) {
      radios[i].checked = true;
      break;
    }
  }

  // Re-render form form.render(&#39;radio&#39;);
});

This code not only shows how to dynamically set the default selection, but also emphasizes the importance of Layui form rendering. The line of form.render(&#39;radio&#39;) is the key, it re-renders all radio boxes to ensure that the user can see the latest status.

However, when using this method, there are several things to note:

  1. Performance considerations : If there are a large number of radio boxes, the traversal operation may affect performance. In this case, it is possible to consider using more efficient selectors or data structures for optimization.
  2. User Experience : Ensure that the default selection settings do not interfere with the user's selection, especially if the user has made the selection before loading the data.
  3. Compatibility : Different browsers may handle checked attributes differently to ensure that your code works properly in various environments.

In a real project, I have encountered an interesting case: In a complex form, different radio box groups need to set default values ​​according to different criteria. To solve this problem, I used a general function to handle the default value settings for all radio boxes:

 function setDefaultRadio(name, value) {
  var radios = document.getElementsByName(name);
  for (var i = 0; i < radios.length; i ) {
    if (radios[i].value === value) {
      radios[i].checked = true;
      break;
    }
  }
  layui.form.render(&#39;radio&#39;);
}

// Use example setDefaultRadio(&#39;sex&#39;, &#39;male&#39;);
setDefaultRadio(&#39;education&#39;, &#39;undergraduate&#39;);

This approach not only improves code reusability, but also makes maintenance easier.

In general, the default selection setting of the Layui radio box seems simple, but there are many factors that need to be considered in actual applications. By combining HTML and JavaScript, we can flexibly deal with a variety of scenarios. Hopefully these experiences and methods will help you use Layui's radio boxes more efficiently in your project.

The above is the detailed content of How to set default selections in the layui radio box. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

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 prohibit image loading by Google Chrome_How to set the image mode without loading by Google Chrome How to prohibit image loading by Google Chrome_How to set the image mode without loading by Google Chrome Sep 18, 2025 pm 04:03 PM

1. You can disable pictures through Google Chrome to improve loading speed, go to Settings → Privacy and Security → Website Settings → Pictures → Select "Don't Show Pictures"; 2. You can also install extensions such as "BlockImage" to achieve flexible control; 3. You can also select "Offline" or "Low-endmobile" mode to test the image-free browsing effect through the network condition simulation function of the developer tool.

TikTok International Edition Official Login Platform TikTok International Edition Quick Entrance Channel TikTok International Edition Official Login Platform TikTok International Edition Quick Entrance Channel Sep 18, 2025 pm 04:15 PM

The official login platform of TikTok international version is https://www.tiktok.com. Users can directly access the website to register or log in, support email or social account binding, intelligently recommend short video content on the homepage, provide multi-language switching, interactive functions and diverse creation tools.

How to set the default location of the download file by Quark Browser_Guide to change the default download path of the file by Quark Browser How to set the default location of the download file by Quark Browser_Guide to change the default download path of the file by Quark Browser Sep 18, 2025 pm 03:54 PM

You can modify the download path of the Quark browser by setting: 1. Go to Settings → Download Management → Default Download Location and select the target folder; 2. If customization is not supported, you can use the file manager to assist in obtaining the path; 3. Advanced users can use the ADB command to modify the application configuration file and force changes to the save directory.

How to view historical download records in QQ browser_QQ browser download history query method How to view historical download records in QQ browser_QQ browser download history query method Sep 18, 2025 pm 04:06 PM

Through the download management page, you can view the history of QQ browser. Open the QQ browser and click the menu in the lower right corner to enter the "Download" option to view all completed, in progress and failed downloads, and support re-downloading, opening or deletion of files.

How to register for iCloud official website_iCloud official website new account registration tutorial How to register for iCloud official website_iCloud official website new account registration tutorial Sep 18, 2025 pm 04:12 PM

You need to register through the AppleID system instead of the iCloud official website, visit appleid.apple.com or create an account on the device, fill in the information, verify the email address number, and then log in to iCloud.

KOOK Voice Platform Official Website _ PC Client and Web Version Login Portal KOOK Voice Platform Official Website _ PC Client and Web Version Login Portal Sep 20, 2025 am 11:30 AM

The official website of KOOK voice platform is https://www.kookapp.cn/, which supports PC client and web version login, and provides multi-terminal coverage for Windows, Android and iOS. Users can download the client or access it directly through the browser.

Frequently Asked Questions about Apple Official Website Login - Solve the Difficulty of Apple Official Website Login Frequently Asked Questions about Apple Official Website Login - Solve the Difficulty of Apple Official Website Login Sep 18, 2025 pm 03:57 PM

1. Check the network connection and try to switch Wi-Fi and mobile data, modify DNS to solve access problems; 2. Accurately enter Apple ID and password to avoid spaces or special characters; 3. Account lock needs to wait 24 hours to avoid repeated attempts; 4. Update the system to the latest version to ensure compatibility; 5. Reset network settings to clear wrong configuration; 6. Visit appleid.apple.com to confirm the account status; 7. Ensure that trusted devices receive verification codes online; 8. Correctly answer security prompt questions; 9. Verify the validity of rescue email; 10. Confirm the trusted phone number to receive text messages; 11. Check SMS filtering to prevent verification codes from being intercepted; 12. Select trusted devices to receive verification codes; 13. Avoid frequent requests for verification codes;

Where to find folders Where to find folders Sep 20, 2025 am 07:57 AM

The most direct way is to recall the storage location, usually in folders such as desktop, documents, downloads, etc.; if it cannot be found, you can use the system search function. File "missing" is mostly due to problems such as unattention of the saving path, name memory deviation, file hiding or cloud synchronization. Efficient management suggestions: Classify by project, time, and type, make good use of quick access, clean and archive regularly, and standardize naming. Windows search and search through File Explorer and taskbar, while macOS relies on finder and Spotlight, which is smarter and more efficient. Mastering tools and developing good habits is the key.

See all articles