Get the current value of the first element in the set of matched elements or set the value of every matched element.
Contents:
-
.val()
- .val()
-
.val( value )
- .val( value )
- .val( function )
.val()Returns: String or Number or Array
Description: Get the current value of the first element in the set of matched elements.
-
version added: 1.0.val()
-
This method does not accept any arguments.
-
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
When the first element in the collection is a select-multiple
(i.e., a select
element with the multiple
attribute set), .val()
returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null
.
For selects, checkboxes and radio buttons, you can use :checked to select the right elements. For example:
1 2 3 4 5 6 7 8 9 10 11 |
|
Note: At present, using .val()
on <textarea>
elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR, however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
1 2 3 4 5 |
|
Examples:
Get the single value from a single select and an array of values from a multiple select and display their values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
Demo:
Find the value of an input box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Demo:
.val( value )Returns: jQuery
Description: Set the value of each element in the set of matched elements.
-
version added: 1.0.val( value )
-
value
A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.
-
-
version added: 1.4.val( function )
-
function
A function returning the value to set.
this
is the current element. Receives the index position of the element in the set and the old value as arguments.
-
This method is typically used to set the values of form fields.
val()
allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like <input type="checkbox">
, <input type="radio">
, and <option>
s inside of a <select>
. In this case, the input
s and the option
s having a value
that matches one of the elements of the array will be checked or selected while those having a value
that doesn’t match one of the elements of the array will be unchecked or unselected, depending on the type. In the case of <input type="radio">
s that are part of a radio group and <select>
s, any previously selected element will be deselected.
Setting values using this method (or using the native value
property) does not cause the dispatch of the change
event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" )
after setting the value.
The .val()
method allows setting the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element’s index and its current value:
1 2 3 |
|
This example removes leading and trailing whitespace from the values of text inputs with a «tags» class.
Examples:
Set the value of an input box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
Demo:
Use the function argument to modify the value of an input box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Demo:
Set a single select, a multiple select, checkboxes and a radio button .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Demo:
Сборник приемов jQuery для работы с текстовыми полями. Во всех примерах используется следующий HTML код:
<input id="text" type="text" name="form-text">
HTML
А jQuery связывается с ним по атрибуту id="text"
(селектор #text
).
1
Получить содержимое текстового поля
$('#text').val();
// или
$('#text').attr('value');
JS
2
Добавить значение в текстовое поле
$('#text').val('Новый текст');
JS
Добавить текст перед и после значения
// Добавить текст в начало
$('#text').val('before ' + $('#text').val());
// Добавить текст в конец
$('#text').val($('#text').val() + ' after');
JS
3
Очистить поле
4
Удалить поле
Метод remove()
удаляет элементы из DOM включая дочерние.
5
Добавить/удалить CSS класс
Метод addClass()
добавляет в атрибут class=""
значение, а removeClass()
удаляет его.
Метод toggleClass()
работает как переключатель, при первом вызове, если у элемента нет такого класса то добавляет, при повторном удаляет его.
// Добавить класс
$('#text').addClass('active');
// Удалить класс
$('#text').removeClass('active');
// Переключить класс
$('#text').toggleClass('active');
JS
6
Фокусировка
Установить фокус
События при смене фокуса
// Событие когда элемент получил фокус
$('#text').focus(function(){
alert('Фокус установлен');
});
// Когда элемент теряет фокус
$('#text').blur(function(){
alert('Фокус снят');
});
JS
7
Выделение всего текста при клике на input
$('#text').focus(function(){
$(this).select();
});
JS
8
Заблокировать и разблокировать input
// Заблокировать
$('#text').prop('disabled', true);
// Разблокировать
$('#text').prop('disabled', false);
JS
9
Подсчет количества символов
<input id="text" type="text">
<p id="result">0</p>
<script>
$('#text').bind('input', function(){
$('#result').html($(this).val().length);
});
</script>
JS
10
Принудительный регистр вводимого текста
// Строчные
$('#text-1').bind('input', function(){
$(this).val($(this).val().toLowerCase());
});
// Заглавные
$('#text-2').bind('input', function(){
$(this).val($(this).val().toUpperCase());
});
JS
11
Запретить копировать, вырезать и вставлять
$('#text').bind('cut copy paste', function(e) {
e.preventDefault();
});
JS
12
Отправить значение через ajax
В примере при каждом изменении поля <input id="text" type="text">
его значение отправляется методом POST на ajax.php.
$('#text').bind('input', function(){
$.ajax({
url: '/ajax.php',
method: 'post',
dataType: 'html',
data: {text: $('#text').val()},
success: function(data){
$('#result').html(data);
}
});
});
JS
You have to use various ways to get current value of an input element.
METHOD — 1
If you want to use a simple .val()
, try this:
<input type="text" id="txt_name" />
Get values from Input
// use to select with DOM element.
$("input").val();
// use the id to select the element.
$("#txt_name").val();
// use type="text" with input to select the element
$("input:text").val();
Set value to Input
// use to add "text content" to the DOM element.
$("input").val("text content");
// use the id to add "text content" to the element.
$("#txt_name").val("text content");
// use type="text" with input to add "text content" to the element
$("input:text").val("text content");
METHOD — 2
Use .attr()
to get the content.
<input type="text" id="txt_name" value="" />
I just add one attribute to the input field. value=""
attribute is the one who carry the text content that we entered in input field.
$("input").attr("value");
METHOD — 3
you can use this one directly on your input
element.
$("input").keyup(function(){
alert(this.value);
});
- Связанные категории:
-
Manipulation
» General Attributes - Forms
- Attributes
#
#
Возвращает или устанавливает значение атрибута value
-
version added: 1.0.val()
нет параметров
-
version added: 1.0.val( value )
value
Тип: Строка или Массив
Строка текста или массив строк, которые для заполнения элемента. Устанавливает значение атрибута value.
-
version added: 1.4.val( function(index, value) )
function(index, value)
Тип: Функция
Атрибуту value будет присвоено значение, которое вернет функция function. Функция для каждого из выбранных элементов. При вызове, ей передаются следующие параметры: index (позиция элемента в наборе) и value (текущее значение атрибута value у элемента).
Метод используется для получения значений элементов формы таких как input, select, textarea. Метод возвращает строку, в случае <select multiple=»multiple»> массив
Для элементов select и чекбоксов, мы можем так же использовать :selected и :checked:
$('select.foo option:selected').val(); // достаём значение из элемента select $('select.foo').val(); // альтернативный способ $('input:checkbox:checked').val(); // достаём значение из чекбокса $('input:radio[name=bar]:checked').val(); // достаём значение из группы радио кнопок
Примеры
Пример: достать значение из элемента select и массив значений из множественного селектов.
<!DOCTYPE html> <html> <head> <style> p { color:red; margin:4px; } b { color:blue; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <p></p> <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select> <script> function displayVals() { var singleValues = $("#single").val(); var multipleValues = $("#multiple").val() || []; $("p").html("<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.join(", ")); } $("select").change(displayVals); displayVals(); </script> </body> </html>
Демо
Пример: получить значение поля input.
<!DOCTYPE html> <html> <head> <style> p { color:blue; margin:8px; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <input type="text" value="some text"/> <p></p> <script> $("input").keyup(function () { var value = $(this).val(); $("p").text(value); }).keyup(); </script> </body> </html>
Демо
Так же мы можем задавать значения.
Примеры
Пример: задаём значение полю input.
<!DOCTYPE html> <html> <head> <style> button { margin:4px; cursor:pointer; } input { margin:4px; color:blue; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <div> <button>Feed</button> <button>the</button> <button>Input</button> </div> <input type="text" value="click a button" /> <script> $("button").click(function () { var text = $(this).text(); $("input").val(text); }); </script> </body> </html>
Демо
Пример: используем функция в качестве аргумента для установки значения input.
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <p>Type something and then click or tab out of the input.</p> <input type="text" value="type something" /> <script> $('input').on('blur', function() { $(this).val(function( i, val ) { return val.toUpperCase(); }); }); </script> </body> </html>
Демо
Пример: задаём значение селекту из одного значения, и множественному селекту, а так же чекбоксам и группе радио кнопок.
<!DOCTYPE html> <html> <head> <style> body { color:blue; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" name="checkboxname" value="check1"/> check1 <input type="checkbox" name="checkboxname" value="check2"/> check2 <input type="radio" name="r" value="radio1"/> radio1 <input type="radio" name="r" value="radio2"/> radio2 <script> $("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check1","check2", "radio1" ]); </script> </body> </html>
Демо
jQuery DOM методы
Определение и применение
jQuery метод .val() получает текущее значение атрибута из первого элемента в наборе совпавших элементов, или устанавливает значение атрибута для каждого соответствующего элемента. Метод .val() используется для получения значений элементов формы, таких как <input>, <select> и <textarea>. При вызове на пустой коллекции, он возвращает undefined.
Обращаю Ваше внимание, что если первый элемент <select> в коллекции с установленным логическим атрибутом multiple (позволяет выбрать несколькой значений), то в этом случае метод .val() возвращает массив, содержащий значение каждого выбранного элемента. В jQuery 3.0, если параметр не указан, то он возвращает пустой массив, до jQuery 3.0, метод возвращает null.
jQuery синтаксис:
// возвращение значений: Синтаксис 1.0: $( selector ).val() // метод не принимает аргументов Возвращает: String, или Number, или Array // установка значений: Синтаксис 1.0: $( selector ).val( value ) value - String, или Number, или Array Синтаксис 1.4: $( selector ).val( function( index, currentValue )) index - Integer currentValue - String
Добавлен в версии jQuery
1.0 (синтаксис обновлен в версии 1.4)
Значения параметров
Параметр | Описание |
---|---|
value | Задает значение для атрибута. |
function(index, currentValue) | Задает функцию, которая возвращает значение, которое будет установлено.
|
Пример использования
<!DOCTYPE html> <html> <head> <title>Использование метода .val() для получения значений</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $( document ).ready(function(){ $( "button" ).click( function(){ // задаем функцию при нажатиии на элемент <button> console.log($( "input" ).val()); // выводим значение первого <input> в наборе console.log($( "select" ).val()); // выводим значение, выбранных <option> элемента <select> }); }); </script> </head> <body> <button>Клик</button> <input type = "text" value = "firstELement"> <input type = "text" value = "secondELement"><br><br> <select multiple> <option selected>First option</option> <option selected>Second option</option> <option selected>Third option</option> <option>Fourth option</option> </select> </body> </html>
В этом примере с использованием jQuery метода .val() мы при нажатии на кнопку выводим в консоль браузера значение первого <input> в наборе и выводим значение, выбранных <option> элемента <select>.
Результат нашего примера:
Рассмотрим пример в котором с помощью метода .val() установим значения:
<!DOCTYPE html> <html> <head> <title>Использование метода .val() для установки значений</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $( document ).ready(function(){ $( "button" ).click( function(){ // задаем функцию при нажатиии на элемент <button> $( "div.firstTest > input").val( "newValue" ); // изменяем значение атрибута элементов <input> внутри элемента <div> с классом firstTest $( "div.secondTest > input").val([ "check1", "check2", "radio2" ]); // изменяем значение атрибута элементов <input> внутри элемента <div> с классом secondTest (что позволяет нам выбрать необходимые элементы) $( "select" ).val([ "Option2", "Option3" ]); // выбираем необходимые элементы раскывающегося списка }); }); </script> </head> <body> <button>Клик</button> <div class = "firstTest"> <input type = "text" value = "firstELement"> <input type = "text" value = "secondELement"><br><br> </div> <div class = "secondTest"> <input type = "checkbox" name = "checkboxname" value = "check1">check1 <input type = "checkbox" name = "checkboxname" value = "check2">check2 <input type = "radio" name = "radio" value = "radio1">radio1 <input type = "radio" name = "radio" value = "radio2">radio2 </div> <select multiple> <option selected>Option1</option> <option>Option2</option> <option selected>Option3</option> <option>Option4</option> </select> </body> </html>
В этом примере с использованием jQuery метода .val() мы при нажатии на кнопку изменяем значение атрибута элементов <input> внутри элемента <div> с классом firstTest, изменяем значение атрибута элементов <input> внутри элемента <div> с классом secondTest (что позволяет нам выбрать необходимые элементы) и выбираем необходимые элементы раскывающегося списка <select>.
Результат нашего примера:
Рассмотрим пример в котором в качестве параметра метода .val() передадим функцию:
<!DOCTYPE html> <html> <head> <title>Использование метода .val() для установки значений (с помощью функции)</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $( document ).ready(function(){ $( "button" ).click( function(){ // задаем функцию при нажатиии на элемент <button> $( "input" ).val( function( index, currentValue ) { // в качестве параметра метода .val() передаем функцию return currentValue.toUpperCase(); // возвращем новое значение атрибута элемента <input> (преобразуем старое значение к верхнему регистру) }); }); }); </script> </head> <body> <button>Клик</button> <input type = "text" value = "firstELement"> <input type = "text" value = "secondELement"><br><br> </body> </html>
В этом примере с использованием jQuery метода .val() и функции, переданной в качестве параметра мы при нажатии на кнопку возвращем новое значение атрибута элемента <input> (преобразуем старое значение к верхнему регистру).
Результат нашего примера: