简体   繁体   中英

I want to insert text using JavaScript when I click on button. But ```.value()``` doesn't seems to work

Here is the code snippet. Please help me out with this bug:/ What I want to do is when I click the button it should insert some value in the input bar

 function insertText() { try { document.querySelector('#input').value('Clicked'); } catch (err) { console.log("ERROR") } }
 * { margin: 0; padding: 0; box-sizing: border-box; }.container { height: 60vh; width: 100vw; display: grid; place-items: center; border: 2px solid blue; }.btn { height: 40vh; border: 2px solid red; width: 100vw; display: grid; place-items: center; }.btn>button { padding: 10px 40px; }
 <div class="container"> <input type="text" value="" id="input"> </div> <div class="btn"> <button oncanplay="insertText()" id="butt">INSERT SOME TEXT</button> </div>

 function insertText(){ try{ document.querySelector('#input').value = "Lorem Ipsum"; }catch(err){ console.log("ERROR"); } }
 *{ margin: 0; padding: 0; box-sizing: border-box; }.container{ height: 60vh; width: 100vw; display: grid; place-items: center; border: 2px solid blue; }.btn{ height: 40vh; border: 2px solid red; width: 100vw; display: grid; place-items: center; }.btn>button{ padding: 10px 40px; }
 <div class="container"> <input type="text" value="" id="input"> </div> <div class="btn"> <button onclick="insertText()" id="butt">INSERT SOME TEXT</button> </div>

You can use this jQuery function to add the text to the input.

 <script>
            $(document).ready(function () {
                $("#setBtnID").click(function () {
                    $("input:text").val("Hello World!");
                });
            });
        </script>

 * { margin: 0; padding: 0; box-sizing: border-box; }.container { height: 60vh; width: 100vw; display: grid; place-items: center; border: 2px solid blue; }.btn { height: 40vh; border: 2px solid red; width: 100vw; display: grid; place-items: center; }.btn>button { padding: 10px 40px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <head> <script> $(document).ready(function () { $("#setBtnID").click(function () { $("input:text").val("Hello World;"); }); }); </script> </head> <body> <div class="container"> <input type="text" value="" id="input"> </div> <div class="btn"> <button id="setBtnID">INSERT SOME TEXT</button> </div> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM