How would you set the default value of a form text field in JavaScript?
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' ;
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>
If you use ID then you have direct access to input in JS global scope
myInput.value = 'default_value'
<input id="myInput">
Instead of using document.getElementById()
you can now use document.querySelector()
for different cases
more info from another StackOverflow answer:
querySelector
lets you find elements with rules that can't be expressed withgetElementById
andgetElementsByClassName
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">
You can also try:
document.getElementById('theID').value = 'new value';
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";