HTML Number defaultValue Property: Number Input Default Value

The HTML Number input defaultValue property is used to set or retrieve the default value of a number input field. This property is particularly useful for providing users with a pre-filled value when the form is initially loaded or reset. It allows developers to specify a numeric value that the input field will display unless the user changes it.

Definition and Purpose

The defaultValue property is an attribute of the HTML <input type="number"> element. It serves the purpose of:

  • Providing a Default Value: Setting a pre-determined value that the number input field will display upon page load.
  • Enhancing User Experience: Guiding users by suggesting a common or expected value.
  • Simplifying Form Completion: Reducing the amount of manual input required from the user.

Syntax

To set or retrieve the defaultValue property, you use JavaScript:

  • Setting the Default Value:
numberInput.defaultValue = value;
  • Retrieving the Default Value:
let defaultValue = numberInput.defaultValue;

Where numberInput is a reference to the <input type="number"> element, and value is the numeric value you want to set as the default.

Attributes

The defaultValue property does not have any specific HTML attributes. It is accessed and manipulated through JavaScript. However, it interacts with the following HTML attributes of the <input type="number"> element:

Attribute Description
`value` The current value of the number input field. This can be different from `defaultValue` if the user has modified the input.
`min` Specifies the minimum allowed value for the number input.
`max` Specifies the maximum allowed value for the number input.
`step` Specifies the legal number intervals for the number input.

Examples

Let’s explore various examples to understand how to use the defaultValue property effectively.

Basic Example: Setting a Default Value

This example demonstrates how to set a default value for a number input field when the page loads.

<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" value="1">

<script>
  const quantityInput = document.getElementById('quantity');
  console.log('Default value:', quantityInput.defaultValue); // Output: 1
</script>

In this case, the value attribute in the HTML sets the initial value, which is then reflected in the defaultValue property when accessed via JavaScript.

Setting defaultValue using JavaScript

Here’s an example of setting the defaultValue dynamically using JavaScript:

<label for="age">Age:</label>
<input type="number" id="age" name="age">

<script>
  const ageInput = document.getElementById('age');
  ageInput.defaultValue = '25';
  console.log('Default age:', ageInput.defaultValue); // Output: 25
</script>

In this example, even though there’s no value attribute in the HTML, setting defaultValue using JavaScript will pre-fill the input with the specified value.

Resetting the Input Field to its Default Value

The defaultValue property is especially useful when you want to reset the input field to its original value.

<form id="myForm">
  <label for="initialValue">Initial Value:</label>
  <input type="number" id="initialValue" name="initialValue" value="50">
  <br><br>
  <button type="button" onclick="resetValue()">Reset Value</button>
</form>

<script>
  const initialValueInput = document.getElementById('initialValue');

  function resetValue() {
    initialValueInput.value = initialValueInput.defaultValue;
  }
</script>

When the “Reset Value” button is clicked, the resetValue() function sets the current value of the input field back to its defaultValue.

Using defaultValue with min and max Attributes

The defaultValue should ideally fall within the range specified by the min and max attributes to ensure validity.

<label for="score">Score (0-100):</label>
<input type="number" id="score" name="score" min="0" max="100" value="75">

<script>
  const scoreInput = document.getElementById('score');
  console.log('Default score:', scoreInput.defaultValue); // Output: 75
</script>

Here, the defaultValue is 75, which is within the acceptable range of 0 to 100.

Dynamic Modification of defaultValue

You can dynamically change the defaultValue property using JavaScript based on certain conditions or user actions.

<label for="quantityAdjust">Adjust Quantity:</label>
<input type="number" id="quantityAdjust" name="quantityAdjust" value="10">
<br><br>
<button type="button" onclick="adjustDefault(5)">Increase Default by 5</button>

<script>
  const quantityAdjustInput = document.getElementById('quantityAdjust');

  function adjustDefault(amount) {
    quantityAdjustInput.defaultValue = parseInt(quantityAdjustInput.defaultValue) + amount;
    quantityAdjustInput.value = quantityAdjustInput.defaultValue;
  }
</script>

Clicking the button will increase the defaultValue and current value by 5 each time.

Retrieving defaultValue After User Input

This example shows how to retrieve the defaultValue even after the user has changed the input field’s value.

<label for="userInput">User Input:</label>
<input type="number" id="userInput" name="userInput" value="20">
<br><br>
<button type="button" onclick="showDefault()">Show Default Value</button>

<script>
  const userInputField = document.getElementById('userInput');
  userInputField.addEventListener('input', function() {
        console.log('Current value:', userInputField.value);
    });
  function showDefault() {
    alert('Default value: ' + userInputField.defaultValue);
  }
</script>

Even if the user changes the value in the input field, clicking the “Show Default Value” button will display the original default value set in the HTML.

Practical Use Cases

  1. Form Reset Functionality: Resetting a form to its initial state, pre-filling fields with their default values.
  2. Preference Settings: Storing user preferences as default values, allowing users to easily revert to these settings.
  3. Default Quantities: Setting a default quantity for products in an e-commerce application.
  4. Configuration Options: Providing a default configuration for software settings, which users can then customize.

Tips and Notes

  • The defaultValue property returns the value as a string. If you need to perform arithmetic operations, ensure you convert it to a number using parseInt() or parseFloat().
  • Setting the defaultValue does not change the current value of the input field if the user has already modified it. To update the current value, you need to explicitly set the value property.
  • Ensure that the defaultValue is a valid number according to the min, max, and step attributes to avoid unexpected behavior.
  • When setting the defaultValue dynamically using JavaScript, it’s a good practice to do so before the user interacts with the input field to avoid confusion.

Conclusion

The HTML Number input defaultValue property is a valuable tool for enhancing the user experience and simplifying form management. By providing a default value, you can guide users, reduce manual input, and easily reset fields to their original state. Understanding and utilizing this property effectively can significantly improve the usability and functionality of your web forms. 📈