Set the value of an input field

前端 未结 15 1528
故里飘歌
故里飘歌 2020-11-22 00:54

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

相关标签:
15条回答
  • 2020-11-22 01:44

    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' ; 
    
    0 讨论(0)
  • 2020-11-22 01:45

    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>
    
    0 讨论(0)
  • 2020-11-22 01:45

    Direct access

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

    myInput.value = 'default_value'
    <input id="myInput">

    0 讨论(0)
  • 2020-11-22 01:46

    2020 Answer

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

    0 讨论(0)
  • 2020-11-22 01:48

    You can also try:

    document.getElementById('theID').value = 'new value';
    
    0 讨论(0)
  • 2020-11-22 01:48

    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";
    
    0 讨论(0)
提交回复
热议问题