Anil P Babu
Anil P Babu

Reputation: 1295

Not able to set hidden input value with jquery

My input control is

<input id="input_id" type="text" hidden value="1"/>

and I try to set value to it using

$('#input_id').val(2);

but I can't. The value is not set. But when I put like this, it works

<input id="input_id" type="hidden" value="1"/>

Any idea why? I am just learning things.

Upvotes: 0

Views: 71

Answers (2)

Akshit Ahuja
Akshit Ahuja

Reputation: 337

<input id="input_id" type="hidden" value="1"/>

is the correct way of creating hidden fields, and you can set the value of this hidden field either by using jquery or by using javascript

$('#input_id').val('2');

OR

document.getElementById('input_id').value = '2';

Upvotes: 0

Brett DeWoody
Brett DeWoody

Reputation: 62743

The value is being set. You can see this in the demo below. The value is set, then console logged to show the updated value. Click the button to display the input and see the updated value.

What I think is confusing you is the value attribute is not changing. If you want to change what's shown in the value attribute use $('#input_id').attr('value', 'new value');

console.log($('#input_id').val());

$('#input_id').val(4);

console.log($('#input_id').val());

$('#input_id').val('abc');

console.log($('#input_id').val());

$('#showInput').click(function() {
  $('#input_id').removeAttr('hidden');
});

$('#updateValueAttr').click(function() {
  $('#input_id').attr('value', $('#input_id').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input_id" type="text" hidden value="1"/>

<button id="showInput">Show Input</button>
<button id="updateValueAttr">Update Input Value Attribute</button>

Upvotes: 2

Related Questions