633

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

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
SebastianOpperman
  • 6,988
  • 6
  • 30
  • 36
  • 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: https://stackoverflow.com/questions/61750165/cant-set-the-value-of-a-file-input-with-javascript – smac89 Sep 16 '22 at 22:48

18 Answers18

1130

This is one way of doing it:

document.getElementById("nameofid").value = "My value";
Community
  • 1
  • 1
James
  • 13,092
  • 1
  • 17
  • 19
  • 7
    I will, is there a way to make the vale NULL if the user clicks on the field ? – SebastianOpperman Sep 30 '11 at 10:46
  • 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 Sep 30 '11 at 10:48
  • 1
    for me it didn't work. will the above create the value attribute? – Dchris Mar 22 '14 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 Aug 05 '16 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 `` 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 Jun 14 '17 at 17:08
  • I don't have element ID, instead I have the name of element. What can I do in this case? – Ripon Al Wasim Jan 11 '18 at 05:46
  • @RiponAlWasim see https://stackoverflow.com/questions/2980830/javascript-getelementbyname-doesnt-work – Jeremy Kahan Mar 07 '18 at 04:19
  • this solution does not work for me. The value is not updated on screen. Is any trick necessary? – Filipe Pinto Jul 18 '19 at 15:50
  • HELP! I do it but the value always change back to original once I click to another field or click to any button on the page. This is the website I do it (with class"_56AraZ") https://shopee.vn/buyer/login?next=https%3A%2F%2Fshopee.vn%2F Can anyone show me how to really set the value to automate login in this website. – Zui Zui Feb 28 '21 at 00:22
  • @JojOatXGME you said what I wanna say. So have you found the answer now? – Zui Zui Feb 28 '21 at 05:43
  • @ZuiZui There is [`element.defaultvalue`](https://html.spec.whatwg.org/multipage/input.html#dom-input-defaultvalue). – JojOatXGME Mar 04 '21 at 23:39
  • 1
    Thanks for this answer! I was trying to use innerHTML and it didn't work. – ClaytonTDM Jun 15 '22 at 14:40
86

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>
TheGoldenTree
  • 158
  • 4
  • 16
Pepe Amoedo
  • 885
  • 6
  • 2
  • 37
    `value` should be accessed directly using dot notation: https://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. – Chris Baker Sep 15 '14 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 Aug 16 '16 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 Feb 27 '17 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 Apr 19 '18 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 Apr 23 '18 at 07:00
64

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' ; 
Varada
  • 16,026
  • 13
  • 48
  • 69
29

2023 Answer

Instead of using document.getElementById() you can now 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">
Runsis
  • 831
  • 9
  • 19
  • 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 May 14 '21 at 07: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 May 14 '21 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 Aug 20 '23 at 16:54
28

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>
David Caissy
  • 2,181
  • 5
  • 24
  • 26
  • 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 Jun 12 '18 at 12:18
  • @tremor totally agreed, and this is the first answer I found using "name" not "id". – avocado Mar 15 '20 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 Mar 11 '21 at 08: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 May 14 '21 at 07:39
  • Thanks. document.getElementByName("timer1") didn't work for me, but document.forms['loginform']['timer1'] did. – Eperbab Feb 20 '22 at 12:47
20

Try out these.

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

// or

var current = document.getElementById("current");
current.value = 12
luis_laurent
  • 784
  • 1
  • 12
  • 32
dallinchase
  • 325
  • 2
  • 3
18

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">
Alexander Johansen
  • 522
  • 1
  • 14
  • 28
php-coder
  • 955
  • 1
  • 12
  • 23
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";
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
8

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" />
  • 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 Aug 06 '14 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 Aug 06 '14 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 –  Aug 15 '14 at 21:20
  • 1
    @Jdoonan not that long ago actually - http://caniuse.com/#feat=input-placeholder placeholder is supported in IE10 and up – danwellman Aug 20 '15 at 14:50
8
document.getElementById("fieldId").value = "Value";

or

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

or

document.getElementById("fieldId").setAttribute('value','Value');
Arun Karnawat
  • 575
  • 10
  • 21
  • 4
    setAttribute('value','Value'); does not set the visible value in the text box for me on Chrome. – Curtis Aug 06 '18 at 06:00
7

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>
ultimatetechie
  • 348
  • 3
  • 14
2

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";
Cake Princess
  • 122
  • 1
  • 9
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>
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Tobiloba
  • 1,618
  • 1
  • 11
  • 7
1

This part you use in html

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

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>
Amranur Rahman
  • 1,061
  • 17
  • 29
0

You can also try:

document.getElementById('theID').value = 'new value';
Bogdan Mates
  • 520
  • 4
  • 8
  • 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. – Daniel Cheung Sep 02 '15 at 12:28
0

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

HTML:

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

JS:

(document.getElementById("smtpHost") as HTMLInputElement).value = data.smtpHost;
Ionut
  • 724
  • 2
  • 9
  • 25
-1

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');