Как изменить значение input jquery

Get the current value of the first element in the set of matched elements or set the value of every matched element.

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

// Get the value from the selected option in a dropdown

$( "select#foo option:checked" ).val();

// Get the value from a dropdown select directly

// Get the value from a checked checkbox

$( "input[type=checkbox][name=bar]:checked" ).val();

// Get the value from a set of radio buttons

$( "input[type=radio][name=baz]:checked" ).val();

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

return elem.value.replace( /r?n/g, "rn" );

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

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<select id="multiple" multiple="multiple">

<option selected="selected">Multiple</option>

<option>Multiple2</option>

<option selected="selected">Multiple3</option>

var singleValues = $( "#single" ).val();

var multipleValues = $( "#multiple" ).val() || [];

// var multipleValues = $( "#multiple" ).val();

$( "p" ).html( "<b>Single:</b> " + singleValues +

" <b>Multiple:</b> " + multipleValues.join( ", " ) );

$( "select" ).change( displayVals );

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

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<input type="text" value="some text">

var value = $( this ).val();

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 inputs and the options 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

$( "input[type=text].tags" ).val(function( index, value ) {

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

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<input type="text" value="click a button">

$( "button" ).click(function() {

var text = $( this ).text();

$( "input" ).val( text );

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

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<p>Type something and then click or tab out of the input.</p>

<input type="text" value="type something">

$( "input" ).on( "blur", function() {

$( this ).val(function( i, val ) {

return val.toUpperCase();

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

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<select id="multiple" multiple="multiple">

<option selected="selected">Multiple</option>

<option>Multiple2</option>

<option selected="selected">Multiple3</option>

<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

$( "#single" ).val( "Single2" );

$( "#multiple" ).val([ "Multiple2", "Multiple3" ]);

$( "input").val([ "check1", "check2", "radio1" ]);

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

i’m trying to use jquery to change the value of an input text box, but it’s not working,
here is my code…

    <form method="get">
            <input id="temp" type="text" name="here" value="temp value" />
            <input class="form" type="radio" value="1" name="someForm" /> Enter something
            Here: <input id="input" type="text" name="here" value="test value" />
    </form>

    <script>

    $(document).ready(function () {
        $('.form').click(function () {
            var newvalue = $("#input").val();
            $("#temp").val(newvalue);
            $("#input").val($("#temp").val());
        });
    });

</script>

the value of the «#input» text box is not changing!!!!!!
why is that???
what am i missing???
thanks a 10 million in advance
p.s. the value of the text box is changing, but the value attribute of the input is NOT!!!
even if i write…

var value = $("#temp").val();
$("#input").attr("value", value);

asked Apr 27, 2010 at 12:19

bombo's user avatar

bombobombo

1,7516 gold badges22 silver badges25 bronze badges

4

The value is not changing because you assign the value that #input already has.


Have a closer look:

var newvalue = $("#input").val();
$("#temp").val(newvalue);
$("#input").val($("#temp").val());
  1. Let value of #input be foo.
  2. You assign newvalue = value of #input = 'foo'
  3. You set the value of #temp:
    value of #temp = newvalue = value of #input = 'foo'
  4. You set the value of #input:
    value of #input = value of #temp = newvalue = value of #input = 'foo'

So depending on which field should get which value you have to change this ;)

answered Apr 27, 2010 at 12:29

Felix Kling's user avatar

Felix KlingFelix Kling

782k173 gold badges1083 silver badges1131 bronze badges

1

You are selecting input not #input so you are setting the value of the first <input> not the element with id="input".

The first input is #temp so you are setting the value of that input to its current value.

answered Apr 27, 2010 at 12:21

Quentin's user avatar

QuentinQuentin

893k122 gold badges1194 silver badges1315 bronze badges

Try:

$("#input").val($('#temp').val());

instead of:

$("input").val($(temp).val());

answered Apr 27, 2010 at 12:22

Sarfraz's user avatar

SarfrazSarfraz

374k77 gold badges529 silver badges576 bronze badges

1

Статья, в которой рассмотрим, какие в jQuery есть методы для чтения и изменения содержимого HTML элементов.

В jQuery имеются три метода, которые позволяют напрямую работать с контентом элемента:

  • html – для чтения и изменения HTML содержимого элемента;
  • text – для чтения и изменения текстового содержимого элемента;
  • val – для чтения и изменения значения элементов формы.

Например, получим HTML содержимое элемента с идентификатором (id) contact:

// сохраним HTML контент элемента в переменную contactHTML
var contactHTML = $('#contact').html();  

Если выборка содержит несколько элементов, то данный метод вернёт HTML контент только первого элемента:

<p>Содержимое 1...</p>
<p>Содержимое 2...</p>
...
<script>
  var htmlContent = $('p').html();
  console.log(htmlContent);
</script>

Для того чтобы получить HTML контент всех найденных элементов необходимо воспользоваться циклом (например, each):

$('p').each(function(){
  // выведем содержимое текущего элемента в консоль
  console.log($(this).html());
});

Изменение HTML контента элемента

Например, заменим содержимое элемента ul:

<ul>
  <li>молоко 1 литр</li>
  <li>яйца 2 шт.</li>
  <li>мука  270 гр.</li>
</ul>
...
<script>
  $('ul').html('<li>молоко 500 мл литр</li><li>яйца 3 шт.</li><li>мука  200 гр.</li>');
</script>

Если на странице будет несколько элементов ul, то данный метод заменит содержимое каждого из них.

Если необходимо изменить контент только у одного элемента на странице, то наиболее просто это сделать через id.

<ul id="ingredients">
  ...
</ul>
...
<script>
  $('#ingredients').html('Новый HTML контент...');
</script>

Использование функции для замены HTML контента элемента:

<h2>Название 1...</h2>
<h2>Название 2...</h2>
<h2>Название 3...</h2>  
...
<script>  
$('h2').html(function(index, oldhtml) {
  // index – индекс элемента в выборке
  // oldhtml – контент элемента
  var newhtml = (index+1) + '. ' + oldhtml;
  return newhtml;
});
</script>

Например, изменим контент элементов (зачеркнём старый контент и добавим рядом новый):

<div class="number">75</div>
<div class="number">37</div>
<div class="number">64</div>
<div class="number">17</div>
<div class="number">53</div> 
...
<script>  
var newNumber = [];
for (var i = 0; i <= 4; i++) {
  newNumber[i] = Math.floor(Math.random() * 99) + 1;
};
$('.number').html(function(index, oldhtml) {
  // index – индекс элемента в выборке
  // oldhtml – контент элемента
  // this – текущий элемент
  // изменим фон текущего элемента на случайный
  $(this).css('background-color','yellow');
  var newhtml = '<s>'+oldhtml+'</s> '+ newNumber[index];
  return newhtml;
});
</script>

Получение текстового содержимого элемента

В jQuery получение содержимого элемента в виде обычного текста осуществляется с помощью метода text. При этом все HTML теги, если они присутствуют в контенте, будут вырезаны.

Например, получим текстовое содержимое элемента p и выведем его в контент другого элемента:

<p id="output"></p>
<button id="get-text">Получить текстовый контент элемента p</button>
<p id="text">Этот параграф содержит <a href="#">ссылку</a>.</p>
...
<script>  
$('#get-text').click(function() {
  var textContent = $('#text').text();
  $('#output').text(textContent);
});
</script>

Метод text также как и html возвращает содержимое только первого элемента выборки (если в ней присутствуют несколько элементов).

Замена контента элемента указанным текстом

Метод text может использоваться не только для чтения, но и для изменения содержимого указанного элемента. При этом HTML теги (если они присутствуют в тексте) будут закодированы с помощью спецсимволов.

<div id="info">
  Некоторый контент...
</div>
...
<script>  
  $('#info').text('<p>Другой контент...</p>');
</script>

После выполнения, элемент div с классом info будет иметь следующий HTML код:

<div id="info">
  &lt;p&gt;Другой контент...&lt;/p&gt;
</div>

На экране данный элемент будет выглядеть так:

<p>Другой контент...</p>

Если в выборке присутствует несколько элементов, то метод text заменит содержимое каждого из них:

<p>Контент 1 ...</p>
<p>Контент 2 ...</p>
<p>Контент 3 ...</p>
...
<script>  
  $('p').text('Новый контент...');
</script>

Использование в качестве параметра метода text функции (добавим в скобках к содержимому каждого выбранного элемента длину его текстовой информации):

<p class="text">Некоторое содержимое...</p>
<p class="text">Ещё некоторый контент...</p>
...
<script>
$('.text').text(function(index,text) {
  // параметры функции: index (порядковый номер элемента в выборке), text (его текущее содержимое)
  var textLength = text.length;
  return text + ' ('+ text.length +')';
});
</script>

Удаление контента элемента

В jQuery для удаления содержимого элемента имеется метод empty. Данный метод не только удаляет элементы, но и другие его дочерние узлы, включая текст.

Например, удалим содержимое всех элементов с классом vote:

<div class="vote">Контент...</div>
...
<script>
  $('.vote').empty();
</script>

Получение значения элемента формы

В jQuery чтение значений элементов input, select и textarea осуществляется посредством метода val.

Например, получим значение элемента input:

<input type="text" id="quantity" name="quantity" value="3" />
...
<script>
// сохраним значение в переменную quantity
var quantity = $('#quantity').val();
// выведем значение переменной quantity в консоль
console.log(quantity);
</script>

Метод val, если в коллекции присутствует несколько элементов, вернёт значение только первого из них.

<input name="color" type="radio" value="white"> Белый<br>
<input name="color" type="radio" value="green" checked> Зелёный<br>
<input name="color" type="radio" value="brown"> Коричневый<br>
...
<script>
  // получим значение первого элемента в коллекции
  var valColor = $('input[name="color"]').val();
  console.log(valColor); // white
  // получим значение выбранной (checked) радиокнопки
  var valCheckedColor = $( "input[type=radio][name=color]:checked" ).val();
  console.log(valCheckedColor); // green
</script>

Для получения значения выбранного элемента (select, checkbox, или radio кнопок) используйте :checked.

// получить значение выбранной опции select
$('select.color option:checked').val();
// получить значение выбранного select
$('select.size').val();
// получить значение отмеченного (checked) checkbox
$('input[type="checkbox"][name="answers"]:checked').val();
// получить значение установленной радиокнопки
$('input[type="radio"][name="rating"]:checked').val();

Если коллекции нет элементов, то метод val возвращает значение undefined.

Например, получим значение элемента textarea, имеющего имя description:

var valDescription =  $('textarea[name="description"]').val();
if (valDescription !== undefined) {
  console.log('Значение элемента textarea: ' + valDescription);
} else {
  console.log('Элемент textarea с именем description на странице не найден!');
}

Получим значение элемента select:

<select id="volume">
  <option>16Gb</option>
  <option>32Gb</option>
</select>
...
<script>
// получим значение выбранной опции элемента select
var volume = $('#volume').val();
// выведем это значение в консоль
console.log(volume);
// выведем значение в консоль при изменении select
$('#volume').change(function(){
  var volume = $(this).val();
  console.log(volume);  
});
</script>

Если элемент select имеет множественный выбор (атрибут multiple), то метод val возвратит в качестве результата массив, содержащий значение каждой выбранной опции (option). Если ни одна опция не отмечена, то данный метод вернёт в качестве ответа пустой массив (до версии jQuery 3 значение null).

<select id="brands" multiple="multiple">
  <option selected="selected">Acer</option>
  <option>Samsung</option>
  <option selected="selected">Asus</option>
</select>

<script>
// var brands = $('#brands').val() || []; // до версии jQuery 3
var brands = $('#brands').val(); // для версии jQuery 3
// преобразуем массив в строку, используя разделитель ", "
var output = brands.join( ", " );
// выведем строку в консоль
console.log(output);
</script>

Установка значения элементу формы

Изменение значения элемента формы в jQuery осуществляется с помощью метода val.

Например, при клике на кнопку установим элементу input её текст:

<div>
  <button>Кнопка 1</button>
  <button>Кнопка 2</button>
  <button>Кнопка 3</button>
</div>
<input type="text" value="Нажмите на кнопку!">
...
<script>
$('button').click(function() {
  var text = $(this).text();
  $('input').val(text);
});
</script>

Данный метод устанавливает значение для всех элементов набора, к которому он применяется.

Например, преобразуем все буквы значения элемента input после потеря фокуса в прописные:

<input type="text" value="Некоторое значение поля">
...
<script>
$('input').on('blur', function() {
  // установим значение полю
  $(this).val(function(index, value) {
    return value.toUpperCase();
  });
});
</script>

Например, поменяем значение элемента select:

<select name="color">
  <option value="red">Красный</option>
  <option value="green" selected>Зелёный</option>
  <option value="blue">Синий</option>
</select>

<script>
// 1 вариант (установим в качестве значения select значение опции blue)
$('select[name="color"] option[value="blue"]').attr('selected', 'selected');
// 2 вариант
$('select[name="color"]').val('blue');
</script>

Например, присвоим значения элементу select с множественным выбором (multiple):

<select id="language" multiple="multiple">
  <option value="english" selected="selected">Английский</option>
  <option value="french">Французский</option>
  <option value="spanish" selected="selected">Испанский</option>
  <option value="china">Китайский</option>
</select>
...
<script>
  $('#language').val(['french', 'china']);
</script>

Изменим, значение checkbox:

<input type="checkbox" name="language" value="english"> Вы знаете английский
...
<script>
  $('input[name="language"]').val('en');
</script>

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed.
    To understand example first few methods to know.
    JQuery val() method:
    This method return/set the value attribute of selected elements.
    If we use this method to return value, it will return the value of the FIRST selected element.
    If we use this method to set value, it will set one or more than one value attribute for set of selected elements.
    Syntax:

    • Return the value attribute:
      $(selector).val()
      
    • Set the value attribute:
      $(selector).val(value)
      
    • Set the value attribute using function:
      $(selector).val(function(index, curValue))
      

    Parameters:

    • value:This parameter is required. It specifies the value of value attribute.
    • function(index, currentValue):This parameter is optional. It specifies the function that returns the value to set.
      • index: It returns the position of index of element in set.
      • currentValue: It returns the current value attribute of the selected elements.

    Example 1: In this example the value of the input element is set by val() method by selecting the input element from its ID.

    <!DOCTYPE HTML>

    <html>

    <head>

        <title>

            JQuery | Set value of input text.

        </title>

        <script src=

        </script>

    </head>

    <body style="text-align: center;">

        <h1 style="color: green;">  

                 GeeksForGeeks  

            </h1> Input Box:

        <input id="input" 

               type="text" 

               class="Disable" 

               value="" />

        <br>

        <br>

        <button id="setText">

            setText

        </button>

        <script>

            $("#setText").click(function(event) {

                $('#input').val("GeeksForGeeks");

            });

        </script>

    </body>

    </html>

    Output:

    Example 2: In this example the value of the input element is set by val() method by selecting the input element from its parent element < body > and then selecting the < input > element.

    <!DOCTYPE HTML>

    <html>

    <head>

        <title>

            JQuery 

          | Set value of input text.

        </title>

        <script src=

        </script>

    </head>

    <body style="text-align: center;">

        <h1 style="color: green;">  

                 GeeksForGeeks  

            </h1> Input Box:

        <input id="input"

               type="text" 

               class="Disable"

               value="" />

        <br>

        <br>

        <button id="setText">

            setText

        </button>

        <script>

            $("#setText").click(

              function(event) {

                $('body input').val(

                  "GeeksForGeeks");

            });

        </script>

    </body>

    </html>

    Output:

    jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
    You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed.
    To understand example first few methods to know.
    JQuery val() method:
    This method return/set the value attribute of selected elements.
    If we use this method to return value, it will return the value of the FIRST selected element.
    If we use this method to set value, it will set one or more than one value attribute for set of selected elements.
    Syntax:

    • Return the value attribute:
      $(selector).val()
      
    • Set the value attribute:
      $(selector).val(value)
      
    • Set the value attribute using function:
      $(selector).val(function(index, curValue))
      

    Parameters:

    • value:This parameter is required. It specifies the value of value attribute.
    • function(index, currentValue):This parameter is optional. It specifies the function that returns the value to set.
      • index: It returns the position of index of element in set.
      • currentValue: It returns the current value attribute of the selected elements.

    Example 1: In this example the value of the input element is set by val() method by selecting the input element from its ID.

    <!DOCTYPE HTML>

    <html>

    <head>

        <title>

            JQuery | Set value of input text.

        </title>

        <script src=

        </script>

    </head>

    <body style="text-align: center;">

        <h1 style="color: green;">  

                 GeeksForGeeks  

            </h1> Input Box:

        <input id="input" 

               type="text" 

               class="Disable" 

               value="" />

        <br>

        <br>

        <button id="setText">

            setText

        </button>

        <script>

            $("#setText").click(function(event) {

                $('#input').val("GeeksForGeeks");

            });

        </script>

    </body>

    </html>

    Output:

    Example 2: In this example the value of the input element is set by val() method by selecting the input element from its parent element < body > and then selecting the < input > element.

    <!DOCTYPE HTML>

    <html>

    <head>

        <title>

            JQuery 

          | Set value of input text.

        </title>

        <script src=

        </script>

    </head>

    <body style="text-align: center;">

        <h1 style="color: green;">  

                 GeeksForGeeks  

            </h1> Input Box:

        <input id="input"

               type="text" 

               class="Disable"

               value="" />

        <br>

        <br>

        <button id="setText">

            setText

        </button>

        <script>

            $("#setText").click(

              function(event) {

                $('body input').val(

                  "GeeksForGeeks");

            });

        </script>

    </body>

    </html>

    Output:

    jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
    You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

    Содержание:

    • .val()

      • .val()
    • .val( value )

      • .val( value )
      • .val( function )
    • Обсуждение
    • Примеры

    Get the current value of the first element in the set of matched elements or set the value of every matched element.

    .val()Возвращает: String or Number or Array

    Описание: Get the current value of the first element in the set of matched elements.

    • Добавлен в версии: 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 also use the :selected and :checked selectors to get at values. For example:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    // Get the value from a dropdown select

    $( "select.foo option:selected").val();

    // Get the value from a dropdown select even easier

    // Get the value from a checked checkbox

    $( "input:checkbox:checked" ).val();

    // Get the value from a set of radio buttons

    $( "input:radio[name=bar]:checked" ).val();

    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

    return elem.value.replace( /r?n/g, "rn" );

    Примеры использования

    .val( value )Возвращает: jQuery

    Описание: Set the value of each element in the set of matched elements.

    • Добавлен в версии: 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.

    • Добавлен в версии: 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 inputs and the options 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

    $( "input:text.items" ).val(function( index, value ) {

    return value + " " + this.className;

    This example appends the string » items» to the text inputs’ values.

    Примеры использования

    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) Задает функцию, которая возвращает значение, которое будет установлено.

    • 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() для получения значений

    Пример использования метода .val() для получения значений

    Рассмотрим пример в котором с помощью метода .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() для установки значений

    Пример использования метода .val() для установки значений

    Рассмотрим пример в котором в качестве параметра метода .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> (преобразуем старое значение к верхнему регистру).

    Результат нашего примера:

    Пример использования метода .val() для установки значений (с помощью функции)

    Пример использования метода .val() для установки значений (с помощью функции)
    jQuery DOM методы

    • Связанные категории:
    • 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>
    

    Демо

    .val()

    Метод позволяет получать и изменять значения элементов форм. Для элементов input это значение атрибута value; для списков выбора (select) – значение value выбранного элемента (в случае множественного выбора – массив значений); в случае с textarea, метод .val() будет работать непосредственно с содержимым тега textarea. Метод имеет три варианта использования:

    возвращает значение атрибута value у выбранного элемента формы. Если выбрано несколько элементов, то значение будет взято у первого. В случае, элемента формы

    <select multiple=»multiple»>

    возвращается массив всех выбранных значений.

    атрибуту value будет присвоено значение newVal, у всех выбранных элементов.

    .val(function(index, newVal)):jQuery1.4

    атрибуту value будет присвоено значение, возвращенное пользовательской функцией. Функция вызывается отдельно, для каждого из выбранных элементов. При вызове, ей передаются следующие параметры: index — позиция элемента в наборе, newVal — текущее значение атрибута value у элемента.

    Примеры использования:

    $(«#surname»).val() вернет значение элемента с идентификатором surname
    $(«.surname»).val() вернет значение первого элемента с классом surname
    $(«input[name=’surname’]»).val() вернет значение первого элемента формы с атрибутом name равным surname
    $(«.surname»).val(«Задерищенко») присвоит значение «Задерищенко» всем элементам формы с классом surname

    Замечание: важно отметить, что используя метод .val(), вы получите значения атрибута value, только у первого элемента из всех выбранных. Если вам нужны значения всех элементов, то следует использовать конструкции типа .map() или .each().

    В действии

    Если в одном из текстовых полей, в которые нужно записывать любимые продукты, значение окажется отличным от «Шоколад», то пользователь получит замечание:

    ~lt~!DOCTYPE html~gt~
    ~lt~html~gt~
    ~lt~head~gt~
      ~lt~script src="https://code.jquery.com/jquery-latest.js"~gt~~lt~/script~gt~
      ~lt~style~gt~
       input{
          width:240px;
          margin:3px;
       }
      ~lt~/style~gt~
    ~lt~/head~gt~
    ~lt~body~gt~
      ~lt~b~gt~Укажите любимые продукты:~lt~/b~gt~~lt~br~gt~
      ~lt~input type="text" value="Колбаса" /~gt~~lt~br~gt~
      ~lt~input type="text" value="Шоколад" /~gt~~lt~br~gt~
      ~lt~input type="text" value="Пиво" /~gt~~lt~br~gt~
      ~lt~input type="text" value="Спагетти" /~gt~ 
    
      ~lt~div id="state"~gt~ ~lt~/div~gt~
    ~lt~script~gt~
        $("input:text").val(
    	  function(index, x){
    	    if(x != "Шоколад")
    	    	return "Шоколад лучше чем " + x;
    	    else
    	    	return x;
    	  }
    	);
    ~lt~/script~gt~
    ~lt~/body~gt~
    ~lt~/html~gt~
    

    Ссылки

    • Список всех функций для манипуляции с элементами страницы

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить значение input javascript
  • Как изменить значение final переменной java
  • Как изменить значение f на фотоаппарате
  • Как изменить значение context react
  • Как изменить значение combobox

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии