Set the value of an input field

Set the value of an input field

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

Solutions/Answers:

Solution 1:

This is one way of doing it:

document.getElementById("mytext").value = "My value";

Solution 2:

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' ; 

Solution 3:

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>

Solution 4:

Try out these.

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

// or

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

Solution 5:

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">

Solution 6:

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>