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

Time:12-29

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 >
  <input type="text" value="" id="input">
</div>
<div >
  <button oncanplay="insertText()" id="butt">INSERT SOME TEXT</button>
</div>

CodePudding user response:

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 >
        <input type="text" value="" id="input">
    </div>
    <div >
        <button onclick="insertText()" id="butt">INSERT SOME TEXT</button>
    </div>

CodePudding user response:

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 >
  <input type="text" value="" id="input">
</div>
<div >
  <button  id="setBtnID">INSERT SOME TEXT</button>
</div>
</body>

  • Related