user3338497 user3338497 - 3 months ago 22
Javascript Question

Add a default value to textbox by Javascript

I am trying to add the value to text box but I don't where I am making mistakes. Can you guys help with this. I cannot add the default value in HTML Tag itself.

<html>
<head>
<script>
$(document).ready(function() {
$("#txtfirstName").val("Your First Name Here!");
$("input[id='txtlastName']").val("Your Last Name Here!");
});
</script>
</head>
<body>


First name:<br>
<input type="text" name="firstname" id="txtfirstName" >
<br>
Last name:<br>
<input type="text" name="lastname" id="txtlastName">

</body>
</html>


FYI: This is just an example page.

Please guide me with this. If this post is not related please don't degrade. Just let me know, I will delete it.

Appreciate your help.

Answer

You need to encase your JavaScript in a script tag. The following code does what you want:

<script   
    src="https://code.jquery.com/jquery-3.1.0.min.js"   
    integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="     
    crossorigin="anonymous"></script>


<script>
    $(document).ready(function() {
        $("#txtfirstName").val("Your First Name Here!");
        $("input[id='txtlastName']").val("Your Last Name Here!");
    });
</script>
<body>


  First name:<br>
  <input type="text" name="firstname" id="txtfirstName" />
  <br>
  Last name:<br>
  <input type="text" name="lastname" id="txtlastName" />


<p>Note that the form itself is not visible.</p>

<p>Also note that the default width of a text input field is 20 characters.</p>

</body>

Also, I changed the way JQuery looks for one of the inputs, so you can see another way of doing it.

EDIT: If you want to do it not using JQuery, the following will do it in plain JavaScript. It uses an IIFE to encapsulate the load function, so extraneous variables and functions to populate the global object (the window object).

<script>
  (function () {
    function init () {
      document.getElementById("txtfirstName").value = "Your First Name Here!"
      document.getElementById("txtlastName").value = "Your Last Name Here!"
    }
    window.onload = init;
  }())
</script>
Comments