Set the value of an input field

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

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

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    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!';

提交回复
热议问题