Advertisement
Advertisement


Set the value of an input field


Question

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

2020/06/26
1
457
6/26/2020 4:12:51 PM

Accepted Answer

This is one way of doing it:

document.getElementById("mytext").value = "My value";
2016/01/10
835
1/10/2016 12:13:13 AM

I use 'setAttribute' function:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>
2014/06/18

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' ; 
2011/09/30

Try out these.

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

// or

var current = document.getElementById("current");
current.value = 12
2012/12/11

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">
2015/09/02

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>
2017/03/17

Source: https://stackoverflow.com/questions/7609130
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]