Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .attr('value') of hidden input element not returning original value from html string?

Basically when invoking .attr("value") over a text box, It will return its value which was set in the markup, not the value which was set by using .val().

For instance,

<input id="test" type="text" value="testing" />

Js:

$("#test").val("hello");
console.log($("#test").val()); //hello
console.log($("#test").attr('value')); //testing

But while doing the same over a hidden element, the result was different like below,

HTML:

<input id="test1" type="hidden" value="testing" />

Js:

$("#test1").val("hello");
console.log($("#test1").val()); //hello
console.log($("#test1").attr('value')); //hello

DEMO

The value attribute got ignored if we set value for that element by using .val(). Anyone have idea on why is this happening? Relevant link which contains details for this behavior would be more helpful.

like image 611
Rajaprabhu Aravindasamy Avatar asked Sep 01 '15 18:09

Rajaprabhu Aravindasamy


People also ask

How do you make a hidden field visible in HTML?

Hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content. A string representing the value of the hidden data you want to pass back to the server.

Is input type hidden safe?

Since they are not rendered visible, hidden inputs are sometimes erroneously perceived as safe. But similar to session cookies, hidden form inputs store the software's state information client-side, instead of server-side. This makes it vulnerable.


1 Answers

Hidden inputs aren't user editable, so you may find that the default and current values are the same for them. So the .val() and .attr('value') are the same for hiddenelement

As far as I get , the value attribute describes the default value for the element, not the current value. Current Value is what you can access through the value property (which is what the jQuery val() does).

like image 72
Tushar Avatar answered Oct 10 '22 13:10

Tushar