- Передать значение переменной javascript во скрытое значение типа ввода
- Script Пример
- 8 ответов
- How to set the value of a input hidden field through javascript?
- Method 1: Using the value Property
- Method 2: Using the setAttribute() Method
- Method 3: Using jQuery
- Input Hidden value Property
- Description
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Как получить значение?
- Как изменить значение value у элемента hidden?
Передать значение переменной javascript во скрытое значение типа ввода
Я хотел бы присвоить значение произведения двух целых чисел в скрытое поле уже в html-документе. Я думал о том, чтобы получить значение переменной javascript, а затем передать его на скрытый тип ввода. Мне сложно объяснить, но так оно и должно работать:
Script Пример
8 ответов
document.getElementById('myField').value = product(2, 3);
Убедитесь, что вы выполняете это задание после полной загрузки DOM, например, в событие window.load .
если у вас уже есть скрытый ввод:
function product(a, b) < return a * b; >function setInputValue(input_id, val)
Если нет, вы можете создать его, добавить в тело и затем установить его значение:
И затем вы можете использовать (в зависимости от случая):
addInput(product(2, 3)); // if you want to create the input // or setInputValue('input_id', product(2, 3));
Просмотрите эту страницу jQuery для некоторых интересных примеров того, как играть с атрибутом value и как его называть:
В противном случае — если вы хотите использовать jQuery вместо javascript для передачи переменных на вход любого типа, используйте установить значение ввода в событии click() , submit() et al:
на каком-либо событии; присвойте или установите значение ввода:
This text will be passed to the input
Используя такой подход, убедитесь, что html-ввод не указывает явно значение или отключенный атрибут.
Остерегайтесь различий betwen .html() и .text() при работе с html-формами.
How to set the value of a input hidden field through javascript?
Setting the value of an input hidden field can be done through JavaScript. Input hidden fields are used to store data on a web page that is not meant to be seen by the user, but rather used for processing by the web page’s scripts. It’s important to understand how to access and modify the value of these fields in order to make changes to the data that’s being stored. In this article, we’ll go over several methods for changing the value of an input hidden field through JavaScript.
Method 1: Using the value Property
To set the value of an input hidden field through JavaScript, you can use the value property. Here is an example code:
// Get the input hidden field element const hiddenInput = document.querySelector('input[type="hidden"]'); // Set the value of the input hidden field hiddenInput.value = 'new value';
- First, we use document.querySelector() to get the input hidden field element. We pass ‘input[type=»hidden»]’ as the selector to select the input element with type=»hidden» .
- Then, we set the value property of the input hidden field element to the new value ‘new value’ .
That’s it! With these two lines of code, you can set the value of an input hidden field through JavaScript.
Here is another example code that shows how to set the value of an input hidden field dynamically based on user input:
label for="username">Username:label> input type="text" id="username"> input type="hidden" id="username-hidden"> script> const usernameInput = document.querySelector('#username'); const usernameHiddenInput = document.querySelector('#username-hidden'); usernameInput.addEventListener('input', (event) => usernameHiddenInput.value = event.target.value; >); script>
- We have an input text field with id=»username» and an input hidden field with id=»username-hidden» .
- We use document.querySelector() to get both input fields.
- We add an event listener to the input text field for the ‘input’ event. This event is triggered every time the user types something in the input field.
- In the event listener, we set the value of the input hidden field to the value of the input text field using the event.target.value property. This way, the value of the input hidden field is updated dynamically based on user input.
I hope these examples help you understand how to set the value of an input hidden field through JavaScript using the value property.
Method 2: Using the setAttribute() Method
To set the value of an input hidden field through JavaScript using the setAttribute() method, follow these steps:
- First, select the input field using document.querySelector() method. For example, to select an input field with an ID of «myInputField», use the following code:
const inputField = document.querySelector('#myInputField');
- Next, use the setAttribute() method to set the value of the input field. For example, to set the value to «Hello, World!», use the following code:
inputField.setAttribute('value', 'Hello, World!');
Here’s the complete code example:
const inputField = document.querySelector('#myInputField'); inputField.setAttribute('value', 'Hello, World!');
You can also set other attributes of the input field using the setAttribute() method. For example, to set the name attribute of the input field, use the following code:
inputField.setAttribute('name', 'myInputFieldName');
You can also set multiple attributes at once using an object. For example, to set both the value and name attributes of the input field, use the following code:
inputField.setAttribute('value', 'Hello, World!'); inputField.setAttribute('name', 'myInputFieldName');
Or, you can use an object to set both attributes at once:
That’s it! Using the setAttribute() method is a simple and effective way to set the value of an input hidden field through JavaScript.
Method 3: Using jQuery
To set the value of an input hidden field using jQuery, you can use the .val() function. Here is an example code:
// Get the input hidden field by its ID var myInput = $('#myInputId'); // Set the value of the input hidden field myInput.val('new value');
In the above example, myInputId is the ID of the input hidden field that you want to set the value for. The .val() function is used to set the value of the input field to ‘new value’ .
Another way to set the value of an input hidden field using jQuery is to use the .attr() function. Here is an example code:
// Get the input hidden field by its ID var myInput = $('#myInputId'); // Set the value of the input hidden field using the attr() function myInput.attr('value', 'new value');
In the above example, myInputId is the ID of the input hidden field that you want to set the value for. The .attr() function is used to set the value attribute of the input field to ‘new value’ .
You can also set the value of an input hidden field using jQuery by chaining the functions together. Here is an example code:
// Set the value of the input hidden field using chaining $('#myInputId').val('new value').attr('value', 'new value');
In the above example, myInputId is the ID of the input hidden field that you want to set the value for. The .val() function is used to set the value of the input field to ‘new value’ , and then the .attr() function is used to set the value attribute of the input field to ‘new value’ .
Input Hidden value Property
Get the value of the value attribute of a hidden input field:
Description
The value property sets or returns the value of the value attribute of the hidden input field.
The value attribute defines the default value of the hidden input field.
Browser Support
Syntax
Return the value property:
Property Values
Technical Details
More Examples
Example
Change the value of the hidden field:
Example
Submitting a form — How to change the value of the hidden field:
document.getElementById(«myInput»).value = «USA»;
document.getElementById(«demo»).innerHTML = «The value of the value attribute was changed. Try to submit the form again.»;
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Как получить значение?
И еще как лучше через аякс получать какие то значения? Например ответ аякса html и несколько значений, я их записываю в хидден а потом по идиотски вытаскиваю. Как лучше это делать?
var $input = $("input:hidden"); // В общем получаете элемент alert($input.val());
если на обычном javascript
var input = document.querySelector("input[type='hidden']"); alert(input.value);
А что касается аякса, что мешает сразу делать с данными то, что вы хотите, не записывая их в input?
shqn: спасибо) Ну не всегда так получается, например нужно получить кусок html и кол-во чего-то, html засунуть в какой то класс, а кол-во чего то заменить в другом месте, как быть в таких ситуациях?)
shqn: я наверно плохо объяснил, но мне кажется этот код не сработает. Смотрите, идет ajax запрос, в переменную data попадает ответ ajax — html. Теперь в переменной data html код, в html коде есть hidden элемент, как через переменную data в которой находится html код, получить значение hiddena?
therealvetalhidden: Обернуть все это в $. То есть будет примерно так:
function(data) var $content = $(data);
var $input = $content.find(«input:hidden»);
alert($input.val());
>
Евгений: спасибо) я как бы вроде понимаю что нужно json но пока его плоха знаю, тем более смотрю далеко не все его юзают, тот же контакт присылает ответ в таком виде 123. А я эти 1 2 3 записываю в хидден и на клиенте их достаю)
therealvetalhidden: JSON как раз юзают все и контакт в том числе! В вк могут некоторые единицы тянуться целым HTML куском, но никак не для передачи данных, а для передачи готового шаблона!) А JSON нечего знать! Это обычный массив, преобразованный в строку специального формата. В PHP json_encode сделает свое дело!
Как изменить значение value у элемента hidden?
Не меняется значение hidden
Имеется форма html: <form action="users/auth.php" method="post" enctype="multipart/form-data".
Как изменить текст элемента, который находится внутри другого элемента?
есть элемент span который находиться внутри элемента р, как сделать так чтобы к примеру вместо .
Как присвоить переменной id элемента и затем изменить класс этого элемента
подскажите пожалуста, как по слику присвоить переменной id элемента (в моем случае элемент<td>) и.
Оптимизация: изменить цвет кнопки и её значение в зависимости от выбранного элемента выпадающего меню
Добрый день! Изучаю jquery c азов, не могли бы подсказать как можно сократить и вообще.
Если не ошибаюсь, то согласно стандарту html элемент input может быть расположен только внутри элемента form.
1 2 3 4 5 6 7 8 9 10 11 12
HEAD>title>/title> script type="text/javascript"> function da_net(e, hf) < alert(document.forms.ololo.hidden_flag1.value); >/script> /HEAD>BODY> a href='#' name='flag1' onclick="da_net(this, 'hidden_flag1')">Да/a> form name="ololo">input type='hidden' name='hidden_flag1' value=1>/form> /BODY>/HTML>
Сообщение от ostgals
Да так получается,но мне надо что бы функция приняла переменные this, и ‘hidden_flag1’ (здесь может быть hidden_flag2 или hidden_flag35 )(т.е. ссылок может быть много а функция одна), и при помощи DOM изменила значение value.
Делаю так:
1 2 3 4 5 6 7 8 9 10 11 12
script type="text/javascript"> function da_net(e, hf){ //hidden_flag1 алертится а ее значение value нет (чаще всего undefined) //alert(hf); //alert(document.forms.ololo.hf.value); if(e.innerHTML == 'Да'){ e.innerHTML = 'Нет'; document.forms.ololo.hf.value = -1; } else{ e.innerHTML = 'Да'; document.forms.ololo.hf.value = 1; } //alert(document.forms.ololo.hidden_flag1.value); alert(document.forms.ololo.hf.value); } script>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
HEAD>title>/title> script type="text/javascript"> function da_net(e, hf) < var HF = document.getElementById(hf); alert(hf+" "+HF.value); if(e.innerHTML == 'Да')< e.innerHTML = 'Нет'; HF.value = -1; >else < e.innerHTML = 'Да'; HF.value = 1; >> /script> /HEAD>BODY> a href='#' name='flag1' onclick="da_net(this, 'hff')">Да/a> input type='hidden' id = 'hff' name='hidden_flag1' value=1>/td> /BODY>/HTML>
Спасибо скрипт меняет значение value.
ЕЩЕ вопрос. Из раздела PHP. Метод POST не читает измененные script-ом значения value
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
HEAD>title>/title> script type="text/javascript"> function da_net(e, hf) < //var HF = document.getElementById(hf); var HF = document.getElementsByName(hf); if(e.innerHTML == 'Да')< e.innerHTML = 'Нет'; HF.value = -1; >else < e.innerHTML = 'Да'; HF.value = 1; >//alert(hf+" "+HF.value); > /script> /HEAD>BODY> form action='q.php' method='POST'> a href='#' name='flag1' onclick="da_net(this, 'hidden_flag1')">Да/a> input type='hidden' name='hidden_flag1' id='hidden_flag1' value=1>/td> a href='#' name='flag2' onclick="da_net(this, 'hidden_flag2')">Да/a> input type='hidden' name='hidden_flag2' id='hidden_flag2' value=1>/td> a href='#' name='flag3' onclick="da_net(this, 'hidden_flag3')">Да/a> input type='hidden' name='hidden_flag3' id='hidden_flag3' value=1>/td> br>br>input type='submit' value='OK'> /form> /BODY>/HTML>
for($i=0; $i4; $i++){ echo $_POST[hidden_flag.$i]; echo "
"; } ?>