Home > Web Front-end > JS Tutorial > jQuery Set Value For Any Type of Input Dynamically

jQuery Set Value For Any Type of Input Dynamically

Jennifer Aniston
Release: 2025-02-28 01:07:13
Original
873 people have browsed it

This jQuery plugin simplifies setting values for various input types dynamically. It addresses the issue of needing different methods for different input types (text, select, checkbox, radio, etc.) by providing a single function.

jQuery Set Value For Any Type of Input Dynamically

The Problem:

Dynamically setting form input values requires different approaches depending on the input type. This plugin aims to consolidate these into a single, reusable function.

Solution:

The $.fn.field plugin provides a unified way to get and set values for any input type within a form.

Usage:

The plugin is used by passing the form's jQuery element, the input name, and the value. For example:

$('#myForm').field('name', 'John Doe');     // Text input
$('#myForm').field('country', 'USA');      // Select
$('#myForm').field('newsletter', true);   // Checkbox
$('#myForm').field('gender', 'male');     // Radio button
Copy after login

Full Code:

(function () {
    $.fn.field = function (inputName, value) {
        if (typeof inputName !== "string") return false;
        const $inputElement = this.find(`[name="${inputName}"]`);

        if (typeof value === "undefined" && $inputElement.length >= 1) {
            switch ($inputElement.attr("type")) {
                case "checkbox":
                    return $inputElement.is(":checked");
                case "radio":
                    let result;
                    $inputElement.each(function () {
                        if ($(this).is(":checked")) result = $(this).val();
                    });
                    return result;
                default:
                    return $inputElement.val();
            }
        } else {
            switch ($inputElement.attr("type")) {
                case "checkbox":
                    $inputElement.prop("checked", value); // Use prop for boolean attributes
                    break;
                case "radio":
                    $inputElement.each(function () {
                        if ($(this).val() == value) $(this).prop("checked", true); // Use prop for boolean attributes
                    });
                    break;
                case undefined: // Handle cases where the element isn't an input
                    this.append(''); // Or handle appropriately for your use case
                    break;
                default:
                    $inputElement.val(value);
                    break;
            }
            return $inputElement;
        }
    };
})();
Copy after login

Improvements:

  • Uses template literals for cleaner string concatenation.
  • Uses .prop("checked") instead of .attr("checked") for setting checkbox and radio button values, which is the recommended approach for boolean attributes.
  • Includes a case undefined to handle situations where the element might not be a standard input type. The current implementation appends an empty string; consider a more robust error handling or alternative action.

This revised plugin offers a more concise and efficient solution for dynamically managing input field values in jQuery. Remember to include jQuery in your project before using this plugin.

The above is the detailed content of jQuery Set Value For Any Type of Input Dynamically. 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