search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
In-depth understanding of jQuery Selectivity plug-in and dynamic option addition
Why don't traditional DOM operations work?
Add options using Selectivity's API method
Detailed explanation of selectivity('add', item) method
Integrate server-side data
Step 1: Serialize server-side data to JSON
Step 2: Loop through and add options in JavaScript
Things to note
Summarize
Home Web Front-end HTML Tutorial Tutorial on dynamically adding new options in jQuery Selectivity plugin

Tutorial on dynamically adding new options in jQuery Selectivity plugin

Nov 27, 2025 pm 10:36 PM

Tutorial on dynamically adding new options in jQuery Selectivity plugin

This tutorial details how to dynamically add new options in the jQuery Selectivity plugin, especially when the data originates server-side. The article emphasizes using the `add` method provided by Selectivity instead of direct DOM manipulation, and guides how to correctly serialize server-side data into JSON format so that JavaScript can smoothly process and update the drop-down list. It also reminds key considerations when placing code in a hybrid development environment.

In-depth understanding of jQuery Selectivity plug-in and dynamic option addition

In modern web development, interactive drop-down lists are common UI components, and plugins such as jQuery Selectivity greatly enhance the experience of native

Why don't traditional DOM operations work?

The Selectivity plugin converts a native element directly through traditional JavaScript DOM operations such as document.getElementById("yourId").options.length = newOption; will not be reflected in the UI rendered by Selectivity. In order to correctly update the contents of the Selectivity drop-down list, we must use the API methods it provides.

Add options using Selectivity's API method

The Selectivity plugin provides specialized API methods to manage its options. Among them, the selectivity('add', item) method is the core for dynamically adding new options.

Detailed explanation of selectivity('add', item) method

  • selectivity('add', item) : This method allows you to add one or more new options to the Selectivity instance.
  • item parameter : item can be an object or an array of objects, each object represents an option to be added. Each options object needs to contain at least id and text attributes:
    • id: The unique identifier of the option, usually the value of the option.
    • text: The display text of the option.

Example: Initialize and add a single option

 // Initialize Selectivity instance $('#example-2').selectivity({
    items: ['Amsterdam', 'Antwerp'], // Initial option multiple: true,
    placeholder: 'Type to search a city'
});

// Dynamically add a new option $('#example-2').selectivity('add', { id: 'London', text: 'London' });

Integrate server-side data

When option data comes from the server side (such as ASP.NET MVC's ViewBag, Model, or obtained through AJAX requests), special attention needs to be paid to the formatting of the data. JavaScript can only understand data in a specific format, the most common and recommended is JSON (JavaScript Object Notation).

Step 1: Serialize server-side data to JSON

On the server side, you need to convert data structures (such as lists, arrays) into JSON strings. In ASP.NET MVC, this can be done using the Json.Encode() method, and Html.Raw() ensures that the output JSON string will not be HTML encoded, so it can be used directly in JavaScript.

Example (in ASP.NET MVC .cshtml file):

Assume that ViewBag.List is a C# object containing a list of strings, such as List {"New York", "Paris", "Tokyo"}.

 //<script> in .cshtml file
    // Convert C# List<string> to JavaScript array const optionsFromServer = @Html.Raw(Json.Encode(ViewBag.List));
    // optionsFromServer will now be [&#39;New York&#39;, &#39;Paris&#39;, &#39;Tokyo&#39;]
</script>

If ViewBag.List contains more complex objects, such as List { new City { Id = "NY", Name = "New York" } }, the JSON encoding will be [{ "Id": "NY", "Name": "New York" }].

Step 2: Loop through and add options in JavaScript

After obtaining the server-side data in JSON format, you can use JavaScript array methods (such as forEach) to traverse the data and call the selectivity('add', item) method for each data item.

Complete sample code (in .cshtml file):

 

    <title>Selectivity dynamically adds options</title>
    <!-- CSS/JS files that introduce jQuery and Selectivity plug-ins -->
    <!-- For example: -->
    <!-- <link rel="stylesheet" href="path/to/selectivity-full.min.css"> -->
    <!-- <script src="path/to/jquery.min.js"></script> -->
    <!-- <script src="path/to/selectivity-full.min.js"></script> -->


    <main>
        <form action="#">
            <div class="form-group col-xs-12 col-sm-4" id="example-2"> </div>
        </form>
    </main>

    <script>
        // 1. Initialize the Selectivity instance $(&#39;#example-2&#39;).selectivity({
            items: [&#39;Amsterdam&#39;, &#39;Antwerp&#39;], // Initial options, can be an empty array multiple: true,
            placeholder: &#39;Type to search a city&#39;
        });

        // 2. Get the data from the server and format it into a JSON array that JavaScript can understand // Assume that ViewBag.List contains [&#39;New York&#39;, &#39;Paris&#39;, &#39;Tokyo&#39;]
        const optionsToAdd = @Html.Raw(Json.Encode(ViewBag.List));

        // 3. Loop through the data and add each option using the &#39;add&#39; method of Selectivity // Note: If optionsToAdd is already in { id: &#39;value&#39;, text: &#39;Display Text&#39; } format,
        //The option object can be passed in directly.
        // If optionsToAdd is just a string array, you need to manually construct the { id, text } object.
        optionsToAdd.forEach((optionText, index) => {
            // Here we assume that what is passed from the server is a string array, and we need to construct the id and text.
            // If the server passes an array of objects, for example [{ Id: &#39;NY&#39;, Name: &#39;New York&#39; }]
            // Then you can write like this:
            // $(&#39;#example-2&#39;).selectivity(&#39;add&#39;, { id: option.Id, text: option.Name });
            $(&#39;#example-2&#39;).selectivity(&#39;add&#39;, { id: optionText, text: optionText });
        });

        // At this point, the Selectivity dropdown should contain the initial options and the options dynamically added from the server side</script>

Things to note

  1. Code placement location : JavaScript code containing @Html.Raw(Json.Encode(ViewBag.List)) must be placed in a file that can execute C# code on the server side (such as a .cshtml file). If this JavaScript code is placed in a separate .js file, the server side will not be able to parse expressions such as @Html.Raw, resulting in an error.
  2. id and text attributes : Ensure that the item object passed to the selectivity('add', item) method contains valid id and text attributes. id is used for internal identification and value storage, and text is used for display.
  3. Data format matching : The structure of the server-side data should match the way you expect { id, text } objects to be constructed on the client side. If the server side directly provides the object array of id and text fields, the client code will be more concise.
  4. Performance considerations : If you need to add a large number of options (e.g. thousands), frequent calls to selectivity('add') may affect performance. In this case, you can consider updating all options at once, or use other methods provided by Selectivity (such as resetting the items attribute) to optimize.

Summarize

Through this tutorial, we learned the correct way to add options dynamically in jQuery Selectivity plugin. The key is:

  1. Avoid direct DOM manipulation and instead use the API methods provided by Selectivity, especially selectivity('add', item).
  2. Properly handle server-side data , serializing it into a JSON format that JavaScript understands.
  3. Pay attention to the deployment environment of the code and ensure that the server-side code is executed in the correct context (such as .cshtml file).

Following these principles, you will be able to flexibly and efficiently manage the options in the Selectivity drop-down list and provide users with a smooth interactive experience.

The above is the detailed content of Tutorial on dynamically adding new options in jQuery Selectivity plugin. 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

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude 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

Popular tool

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)

Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Mar 09, 2026 pm 08:15 PM

When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.

A complete guide to using the keyboard to control the smooth movement of HTML elements A complete guide to using the keyboard to control the smooth movement of HTML elements Mar 13, 2026 pm 10:18 PM

This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.

Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Mar 12, 2026 pm 08:51 PM

This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.

How to optimize Lighthouse image scoring while maintaining high image quality How to optimize Lighthouse image scoring while maintaining high image quality Mar 11, 2026 pm 09:39 PM

This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.

How to dynamically pass HTML form data to analytics.track() method How to dynamically pass HTML form data to analytics.track() method Mar 13, 2026 pm 10:57 PM

This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.

How to properly override default styles and implement custom CSS layouts in Divi theme builder How to properly override default styles and implement custom CSS layouts in Divi theme builder Mar 14, 2026 am 12:00 AM

This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.

How to add prompt copy for disabled button click How to add prompt copy for disabled button click Mar 30, 2026 pm 04:30 PM

This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.

How to switch images by clicking a button (elegant implementation based on jQuery) How to switch images by clicking a button (elegant implementation based on jQuery) Apr 04, 2026 pm 08:06 PM

This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.

Related articles