Setting Input Values In jQuery With The val() Method

heap sort in cSometimes you need to set the value of an input field in a web page  —  after you’ve created the input.  When that happens, who you gonna call?  The jQuery val() method, that’s who!  you can set input values after the fact, and do a few other good tricks in the process.

If you want to find out more about what you can do with jQuery or JavaScript, check out some of the excellent courses that are available online.

jQuery In 30 Seconds

But first, are you ready for the world’s quickest recap of jQuery?  Here it is:

jQuery is an open-source library that extends the capabilities of JavaScript.  It has its own, somewhat quirky syntax (doesn’t everything?), which goes something like this:

$("select_something").do_something('argument 1","argument 2", etc.)

Doing Something With val()

The val() method is one of the “.do_something” commands.  The val() method is specifically designed to work with the HTML <input> tag —  it operates on the input value (the text entered or item selected).

val() actually serves two functions  —  it can retrieve the current input value, and it can set that value.  For the most part, we’re going to be talking about setting the value (although we will use the retrieved value in connection with the callback function, discussed later in this article).

val() Is Not The Value Attribute

First, though, a note on setting input values.  When you create an <input> tag in HTML, you can optionally set the default value (which the user can then change) by using the “value=” attribute.  The val() method, however, does something a little bit different  —  it sets the value after the input is created, and very possibly after the user has already entered a value.  That’s probably not something that you would want to do with most inputs, but there are times when you may want to do it  —  in response, for example, to a user selection that is designed to automatically fill in input fields with predetermined values, or, as we will discuss below, in order to perform an operation on the user input.

How val() Works

Let’s take a look at how val() works.  The following code shows val() at work with basic user input  —  the user enters some text in the input field, then clicks on a button, which triggers the function that uses val(). (In this example, we even provide the default text, using the HTML “value=” attribute described above, so all the user needs to do is click on the button.)

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#dosomething").click(function(){
    $("#deftext").val("Cindy");
  });
});
</script>
</head>
<body>
<input type="text" id="deftext" value="Fred" > <br>
<button id="dosomething">OK</button>
</body>
</html>

What does it do?  It gives you an input window, displaying the default text, “Fred”.  You can enter new text, or leave it as-is.  In either case, if you click on the OK button, the current text is replaced by “Cindy”.

A Little Housekeeping

Before we get to val() itself, we’ll go over a few other items you should know about.  First, this line (or something similar) is necessary for using jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

It links to an instance of the jQuery library  —  in this case, an online jQuery source, although it could just as easily link to a local copy of the library.

Ready, Steady, Go!

Now look at these lines:

$(document).ready(function(){
...
  });

The ready() method checks to make sure that the page is fully loaded before running the contents of (function(){ … })  —  which is where we put our main jQuery code.

We create a button, so the user can trigger the action:

<button id="dosomething">OK</button>

And the val() method runs as a function of the click() method, which is actually what’s triggered when the user clicks on the button:

 $("#dosomething").click(function(){
   ...
  });

val() In Action:  The Details

So what does val() do?  The code is pretty simple:

$("#deftext").val("Cindy");

The $ just says that what follows will be jQuery code.  First, it selects the HTML element with the ID “deftext”.  Then it changes that element’s value to “Cindy”.

Note that “deftext” has to be a form field, because that’s what val() works with.  If you change it to some other type of HTML element, val() won’t do anything. (You can use the text() or html() methods to change a text or HTML element in a similar manner.)

Including The User’s Input

You can do more than just change the value of the input field, however.  val() has a built-in callback function, which retrieves two items of data from the form field:  the element’s index in the list of selected elements (which is useful in some circumstances, but not necessary for our example), and the current value of the input field, which is frequently a very important item.  After you have retrieved the current value, you can use it as part of the new value, perhaps after adding something to it, or performing an operation on it.

val() Callback Example

In the following example, we ask the user to enter his or her name, and then select a royal title by clicking on the appropriate button.  We then add the title to the user’s name, and display it in the original input form field:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#king").click(function(){
    $("#yourname").val(function(i,origText){
    return "His Royal Highness, King " + origText; 
    });
  });
    $("#queen").click(function(){
    $("#yourname").val(function(i,origText){
    return "Her Royal Highness, Queen " + origText; 
    });
  });
    $("#princess").click(function(){
    $("#yourname").val(function(i,origText){
    return "Supreme Princess " + origText + " of Rainbow Sparkle Land"; 
    });
  });
});
</script>
</head>
<body>
<p>Give yourself a royal title!</p>
<p>Enter your name: <input type="text" id="yourname" size = "100" > </p>
<p>Now choose your title:</p>
<button id="king">King</button>&nbsp; <button id="queen">Queen</button>&nbsp; 
 <button id = "princess">Princess</button>
</body>
</html>

Giving The User A Choice

This example is a little more elaborate, but for the most part, it’s very similar to our first example.  It has three buttons, each with its own ID and val() operation, but, with the exception of the callback function, each button operates in much the same way as the one in the first example.  The callback function itself is the only real difference:

  $("#yourname").val(function(i,origText){
    return "His Royal Highness, King " + origText; 
    });

It retrieves the index, “i”, and the current input field value, “origText”.  Then it uses the “return” option to set the new value  —  in this case, a string made up of the title (“His Royal Highness, King “) plus the current value, represented by origText. Paste the code into a text file with the extension .htm, then open it in a browser to try it out!

There is, of course, much more that you can do with jQuery, with JavaScript, and with HTML.  You can find out more about web design and programming by taking some of the many online classes, ranging from beginning to advanced, that are available in these and other subjects.