jQuery Set Value For Any Type of Input Dynamically

Share this article

Quick share of a problem I had solved for setting form input values dynamically irrelevant of the input type. Hopefully will help someone out there.

Problem

Setting form input values dynamically for input, select, checkbox, radio etc… they all have different methods of setting values. So I was looking for just 1 function which could be passed the input element and set the value based on the input type. As you may know if you use :input this grabs all inputs on a form:
$('form :input');
I have looked at something similar before for an auto form filler
. And also for a field get and set function. Also to get the type of an input is fairly easy:
$('form #input').attr('type');

Usage

You pass through the form as the jQuery DOM element against the field function with 2 parameters for input name and value to get/set. Easy as pie!
$('#form').field('name', 'sam deering'); //text
$('#form').field('frequency', '20'); //select
$('#form').field('subscribe', 'true'); //checkbox
$('#form').field('language', 'jquery'); //radio
etc...

Full Code

//field function to get/set input values of any type of input
(function () {
    $.fn.field = function (inputName, value)
    {
        console.log('field called...');
        console.log($(this));

        console.log(typeof inputName);

        if (typeof inputName !== "string") return false;
        var $inputElement = $(this).find("[name=" + inputName + "]");
        // var $inputElement = $(this); //direct mapping with no form context

        console.log($inputElement);

        if (typeof value === "undefined" && $inputElement.length >= 1)
        {
            switch ($inputElement.attr("type"))
            {
                case "checkbox":
                    return $inputElement.is(":checked");
                    break;
                case "radio":
                    var result;
                    $inputElement.each(function (i, val) {
                        if ($(this).is(":checked")) result = $(this).val()
                    });
                    return result;
                    break;
                default:
                    return $inputElement.val();
                    break;
            }
        }
        else
        {
            switch ($inputElement.attr("type"))
            {
                case "checkbox":
                    $inputElement.attr({
                        checked: value
                    });
                    break;
                case "radio":
                    $inputElement.each(function (i) {
                        if ($(this).val() == value) $(this).attr({
                            checked: true
                        })
                    });
                    break;
                case undefined:
                    $(this).append('');
                    break;
                default:
                    $inputElement.val(value);
                    break;
            }
            return $inputElement;
        }
    }
})();

Frequently Asked Questions (FAQs) about Dynamically Setting Input Types with jQuery

How can I dynamically change the value of an input field using jQuery?

To dynamically change the value of an input field using jQuery, you can use the .val() method. This method is used to get the current value of the first element in the set of matched elements or set the value of every matched element. Here’s an example:

$('input').val('New Value');

In this example, ‘New Value’ will be the new value of the input field.

Can I use jQuery to change the type of an input field dynamically?

Yes, you can use jQuery to change the type of an input field dynamically. However, due to restrictions in Internet Explorer, the type of an input field cannot be changed directly. Instead, you can clone the input field, set the new type, and replace the old input field with the new one. Here’s an example:

var newInput = $('input').clone();
newInput.attr('type', 'newType');
$('input').replaceWith(newInput);

In this example, ‘newType’ is the new type of the input field.

How can I set the value of a file input field dynamically using jQuery?

Due to security reasons, browsers do not allow scripts to change the value of a file input field dynamically. This is to prevent malicious scripts from uploading files without the user’s consent. However, you can reset the value of a file input field by replacing it with a new input field.

Can I use jQuery to create input fields dynamically?

Yes, you can use jQuery to create input fields dynamically. You can use the .append() or .html() methods to add new input fields to the DOM. Here’s an example:

$('form').append('<input type="text" name="newInput">');

In this example, a new text input field named ‘newInput’ is added to the form.

How can I get the value of a dynamically created input field using jQuery?

You can get the value of a dynamically created input field using the .val() method, just like any other input field. However, since the input field is created dynamically, you need to use event delegation to bind events to it. Here’s an example:

$(document).on('change', 'input', function() {
console.log($(this).val());
});

In this example, the value of the input field is logged to the console whenever it changes.

Can I use jQuery to change the attributes of an input field dynamically?

Yes, you can use jQuery to change the attributes of an input field dynamically. You can use the .attr() method to get or set the value of any attribute of an input field. Here’s an example:

$('input').attr('placeholder', 'New Placeholder');

In this example, the placeholder of the input field is changed to ‘New Placeholder’.

How can I use jQuery to disable or enable an input field dynamically?

You can use jQuery to disable or enable an input field dynamically by changing the ‘disabled’ attribute. Here’s an example:

$('input').attr('disabled', true); // To disable
$('input').attr('disabled', false); // To enable

In this example, the input field is disabled or enabled based on the value of the ‘disabled’ attribute.

Can I use jQuery to change the name of an input field dynamically?

Yes, you can use jQuery to change the name of an input field dynamically. You can use the .attr() method to change the ‘name’ attribute of an input field. Here’s an example:

$('input').attr('name', 'newName');

In this example, the name of the input field is changed to ‘newName’.

How can I use jQuery to change the size of an input field dynamically?

You can use jQuery to change the size of an input field dynamically by changing the ‘size’ attribute. Here’s an example:

$('input').attr('size', '30');

In this example, the size of the input field is changed to ’30’.

Can I use jQuery to change the maxlength of an input field dynamically?

Yes, you can use jQuery to change the maxlength of an input field dynamically. You can use the .attr() method to change the ‘maxlength’ attribute of an input field. Here’s an example:

$('input').attr('maxlength', '10');

In this example, the maxlength of the input field is changed to ’10’.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week