666

How would you set the default value of a form <input> text field in JavaScript?

2
  • 1
    I just wanted to point out that depending on the type of your input field, it may not allow setting its value if it is a file. See this question: stackoverflow.com/questions/61750165/…
    – smac89
    Commented Sep 16, 2022 at 22:48
  • 3
    What do you mean by “the default value”?
    – dumbass
    Commented Oct 11, 2024 at 6:41

19 Answers 19

1166

This is one way of doing it:

document.getElementById("nameofid").value = "My value";
11
  • 4
    Yes, assign an event handler to the input field that wipes the value onclick. Example: elem.onclick = clearField(); // that would point to a function that wipes the field by setting the value to nothing, similar to the answer above.
    – James
    Commented Sep 30, 2011 at 10:48
  • 1
    for me it didn't work. will the above create the value attribute?
    – Dchris
    Commented Mar 22, 2014 at 11:44
  • 2
    This doesn't seem to work if you're trying to change the value for the input-tag itself. To clarify, if I have a button that should change its value when it is clicked, I don't seem to be able to change it, neither by "this.parentNode.getElementByTagName('input').style.display='none';" nor by using this.style.display='none'; Also, I even tried to use ".style = display: none;';" with no success...
    – MahNas92
    Commented Aug 5, 2016 at 19:00
  • 13
    This and other answers to the question above seems to ignore that the default value shall be changed. Using .value = ... does change the current value only. Resetting the form (with <input type="reset" /> for example) will change the value back to the original one. In contrast, setAttribute("value", ...) works properly in Firefox and Chrome. The default value is changed but the actual value is only changed if the user have not modified it already. However, setAttribute is not recommended because of browser compatibility. Is there any other possibility?
    – JojOatXGME
    Commented Jun 14, 2017 at 17:08
  • 1
    Thanks for this answer! I was trying to use innerHTML and it didn't work.
    – ClaytonTDM
    Commented Jun 15, 2022 at 14:40
90

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>
5
  • 38
    value should be accessed directly using dot notation: developer.mozilla.org/en-US/docs/Web/API/Element.setAttribute you only use set/getAttribute to deal with the original value. After DOM is loaded, .value represents the actual working value of the element. Commented Sep 15, 2014 at 20:06
  • 6
    @ChrisBaker I would +1000 this answer if I could. I have a 3rd party app that scans input fields to automate the application (my page renders in an embedded ie Control). This is a unique scenario where input fields are consumed by the client's app. Input fields were not reset immediately after postback using .value in my document ready function. When I had a subsequent async postback the user would initiate, it would reuse these input values to automate something they clicked on earlier and I needed the page to "forget them". This is the hacky magical sauce I needed. Thank you Pepe and Chris!
    – MikeTeeVee
    Commented Aug 16, 2016 at 16:22
  • 4
    I'm using Yii 2.0 and setting the .value = '' directly wouldn't properly run form validation on the field. Using setAttribute('value','...') is properly handled. thanks!
    – ekscrypto
    Commented Feb 27, 2017 at 13:33
  • 1
    I have a strange problem that solved with setAttribute. My problem was changing value of an input through a function call, change last changed inputs too.
    – SAMPro
    Commented Apr 19, 2018 at 21:43
  • 1
    I could set value to a pop-up modal input (text) only using this answer. .value did not work for me. Thank you
    – Ula
    Commented Apr 23, 2018 at 7:00
63

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 
1
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:14
28

Instead of using document.getElementById() you can use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

4
  • 2
    Do you want to add it to your answer or should I post a new answer: document.querySelector("#name").value='foo' works with id which is widely used.
    – Timo
    Commented May 14, 2021 at 7:52
  • 1
    @Timo Well my answer answers the question, querySelector can have multiple rules. Your comment is helpful! I will upvote it but I wouldn't post a new answer because it is the same
    – Runsis
    Commented May 14, 2021 at 16:10
  • If the elements have id defined, better to use getElementById() as it could be miles faster than querySelector(), especially on larger pages.
    – manikanta
    Commented Aug 20, 2023 at 16:54
  • @manikanta Why would it be "miles faster"? Do you think it's really expensive for querySelector() to tell that #foo is just an ID and it can simply call getElementById() internally?
    – Barmar
    Commented Feb 2 at 4:10
27

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>
6
  • 4
    The reason I like this answer, is that you use the "name" attribute of the form rather than the DOM element ID, why add an ID field to each of the form inputs when you don't need to?
    – tremor
    Commented Jun 12, 2018 at 12:18
  • @tremor totally agreed, and this is the first answer I found using "name" not "id".
    – avocado
    Commented Mar 15, 2020 at 18:23
  • What is more efficient, retrieving the value by input id or by form and input name? seems like there are not many forms on the page but many elements.
    – oCcSking
    Commented Mar 11, 2021 at 8:34
  • Using your code to set the input value via the form element, it does not get updated in the html on the site. When I address the input directly, it gets updated.
    – Timo
    Commented May 14, 2021 at 7:39
  • Thanks. document.getElementByName("timer1") didn't work for me, but document.forms['loginform']['timer1'] did.
    – Eperbab
    Commented Feb 20, 2022 at 12:47
18

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12
2
  • 2
    Never set non-text values to such fields. If you read back you will read string (!) in some browsers )
    – socketpair
    Commented Apr 4, 2014 at 14:21
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:14
16

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">
1
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:13
12
<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";
1
  • This sets the current value, not the default value. If you use the form's Reset button it will revert back to the default.
    – Barmar
    Commented Feb 2 at 4:10
7

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />
5
  • 1
    The problem with this is that it doesn't work for Internet Explorer at all. If you know you aren't going to have IE clients, then yes, this is the best answer.
    – Sifu
    Commented Aug 6, 2014 at 15:57
  • 2
    @Sifu This is probably actually a good thing to do even if you do know you have IE clients (possibly in addition to a JavaScript solution) as it will also re-set the value when the field is emptied.
    – ahruss
    Commented Aug 6, 2014 at 16:03
  • 1
    @Sifu when did IE not support the placeholder attribute, use IE and go to www.1c3br3ak3r-multimedia.ca and look at the search bar, it uses the placeholder attribute
    – user3915050
    Commented Aug 15, 2014 at 21:20
  • 1
    @Jdoonan not that long ago actually - caniuse.com/#feat=input-placeholder placeholder is supported in IE10 and up
    – danwellman
    Commented Aug 20, 2015 at 14:50
  • 1
    What does placeholder have to do with the default value?
    – Barmar
    Commented Feb 2 at 4:14
6
document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');
2
  • 4
    setAttribute('value','Value'); does not set the visible value in the text box for me on Chrome.
    – Curtis
    Commented Aug 6, 2018 at 6:00
  • @Curtis It does, until the value has been manually edited. See my answer.
    – connexo
    Commented Feb 3 at 20:59
5

It's simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>
1
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:14
5

As of today (2025-02-03), none of the other answers comes even close to adequately answer the question. And yes, this is much more complicated than the average developer would like it to be, and also than the question would make you expect.

Let's dive in and shed some light on the matter!

Setting the Default Value of an Input Element: value vs defaultValue, attribute vs property

It's important to understand the distinction between the value attribute and the value property (also sometimes called IDL attribute) when working with input elements in HTML and JavaScript. These two serve different purposes and understanding their roles will allow you to effectively manage the initial and current values of an input field.

1. The value Attribute

The value attribute is primarily used to set the initial value of an input element when the HTML is first parsed by the browser. This initial value is also known as the default value.

The corresponding JavaScript property for this attribute is not value, but rather defaultValue. Essentially, the defaultValue property is a reflection of the value attribute:

get defaultValue() { return this.getAttribute('value') ?? ''; }
set defaultValue(val) { this.setAttribute('value', val); }

Here, this refers to the input element. As you can see, the value attribute and the defaultValue property are always in sync.

However, there's a caveat: if the user has not yet interacted with the input field, programmatically setting the value attribute via setAttribute will also update the current value of the input, which is represented by the value property. This synchronization stops as soon as the user modifies the input field.

2. The value Property

The value property represents the current value of the input field.

If the input field had an initial value (set declaratively via the value attribute, in the HTML) and the user modifies this value, the value attribute and the value property will no longer be in sync. Once the input field is "dirty" (i.e., user-modified), setting the value attribute will no longer affect the current value.

3. value attribute vs defaultValue property vs value property - in real code

This code example demonstrates the behavior of the value attribute, defaultValue property, and value property. Experiment with the different buttons, observe the log output, and note how the behavior changes once you manually modify the input field's value.

const input = document.getElementById('input');

function inspectValues() {
  console.log('value attribute: ' + input.getAttribute('value'));
  console.log('defaultValue property: ' + input.defaultValue);
  console.log('value property: ' + input.value);
  console.log('--------------------------------------');
}

function setViaAttribute() {
  input.setAttribute('value', 'set via value attribute');
  inspectValues();
}

function setViaDefaultValue() {
  input.defaultValue = 'set via defaultValue property';
  inspectValues();
}

function setViaValueProperty() {
  input.value = 'set via value property';
  inspectValues();
}
<input id="input" value="foo">
<button type="button" onclick="inspectValues()">Inspect</button>
<button type="button" onclick="setViaAttribute()">Set via value attribute</button>
<button type="button" onclick="setViaDefaultValue()">Set via defaultValue property</button>
<button type="button" onclick="setViaValueProperty()">Set via value property</button>

0
1
<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>
1
  • This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:12
1

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";
1
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:12
0

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>
1
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:12
-1

 
      function GetAmount()
      {
      var insertNow = document.getElementById("insert").value;
      document.getElementById("output").setAttribute('value',insertNow);
      }
   
  <label>Capture input box</label>
  <br clear="all"/>
  <input id="insert">
  <input onClick="GetAmount()" type="submit" title="Submit">
  <br/>

   <label>Display input box</label>
   <form>
   <input id="output" value="">
   <input type="submit" title="Submit">
   </form>

   

-2

You can also try:

document.getElementById('theID').value = 'new value';
1
  • 4
    Setting a new value isn't setting the default value. Therefore, this doesn't solves the problem. You should say that as the comment of the post once you've gain enough reputation. Commented Sep 2, 2015 at 12:28
-2

HTML:

<input id="smtpHost" type="user" name="smtpHost">

JS:

(document.getElementById("smtpHost") as HTMLInputElement).value = data.smtpHost;
3
  • 1
    as HTMLInputElement is Typescript, isn't it? Commented Apr 4, 2023 at 13:04
  • Yes, it is Typescript.
    – Ionut
    Commented Apr 7, 2023 at 10:24
  • 1
    This sets the current value, not the default value.
    – Barmar
    Commented Feb 2 at 4:11
-4

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');
3
  • 1
    Please test easily testable code before submitting. The code you have posted does not work as posted. Commented Apr 4, 2023 at 17:07
  • You're missing the call to jQuery()
    – Barmar
    Commented Feb 2 at 4:11
  • Strings don't have a .attr property, let alone a method by that name.
    – connexo
    Commented Feb 3 at 21:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.