Method val
The val method allows you to get and change the current value of an element.
Syntax
This way we can get the current value of the first element in the set:
$(selector).val();
The val method is mainly used to get the values of form elements, such as: input, select and textarea. If called on an empty collection, it will return undefined. When working with select with the multiple attribute set, the method will return an array of values for each selected option. If none of them are selected, an empty array will be returned. This way we can set the value of each element in the set. You can pass a string, array, or number as a parameter:
$(selector).val(value);
Applying a function to each element in a set. The function takes the current number in the set as its first parameter, and its current value as its second parameter:
$(selector).val(attribute name, function(number in set, current value));
Example
In the following example, let's get the values entered into the input and output them below in the paragraph:
<input type="text" value="text">
<p></p>
p {
color: green;
margin: 8px;
}
$('input').keyup(function() {
let value = $(this).val();
$('p').text(value);
}).keyup();
Example
Now, using the val method, we will write the values of the buttons that we will press to the input below:
<div>
<button>one</button>
<button>two</button>
<button>three</button>
<button>four</button>
</div>
<input type="text" value="click buttons">
button {
margin: 4px;
cursor: pointer;
}
input {
margin: 4px;
color: green;
}
$('button').click(function() {
let text = $(this).text();
$('input').val(text);
});