0

I work with jquery and try to change attribute "value=Hello" to "value=admin" in input tag. but I don't understand why I can't do this. When I run my example I don't have the result in Google Chrome debugger.

!DOCTYPE html>
<html>
<head>     
    <script src="jquery-1.10.2.js"></script>
    <script>     
        $(document).ready(function () {     
          $("input[type=text]").val("admin");
           alert( $("input[type=text]").val());
        });     
    </script>        
</head>
<body>
    <span>Login</span><input type="text" value="Hello" /><br />
    <span>Password</span><input type="password" />
</body>
</html>
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
Makeda
  • 47
  • 4

2 Answers2

1

Try

$("input[type=text]").attr('value', 'admin')

Although your method should already work, this is an alternative to try if somehow you can't get .val() working. Using .attr(), you are manually editing the value attribute on your input which is what you want.

If you want to see the change, simply console.log( $("input[type=text]").val() )

davidxd33
  • 1,186
  • 4
  • 22
  • 38
  • Why make it more complicated? – UweB Jul 22 '14 at 12:59
  • `for(var i=0;i<1000;i++){ $("input[type=text]").attr('value', 'admin'); }` This is also another way of implementing it..! Would you suggest this..? – Balachandran Jul 22 '14 at 13:01
  • I wouldn't because now you're over complicating it. – davidxd33 Jul 22 '14 at 13:02
  • I know his method works, I'm not stupid. This is an alternative and more understandable. – davidxd33 Jul 22 '14 at 13:02
  • OK. Thanks. What difference between attr() and value(). What exactly I add if use val() and where I can see this value. – Makeda Jul 22 '14 at 13:07
  • Attr() is used to edit any attribute on an element. If you want to see the value, just console.log the val() or this. – davidxd33 Jul 22 '14 at 13:09
  • Although your answer in itself is correct, it is not very helpful. Please consider extending it for why `attr('value')` is different from `val()`. Short answers like these, that do not provide good explanations go up for moderation for deletion, **as it is currently the case with your answer.** – rioki Jul 22 '14 at 13:33
0

jQuery's .val() function refers to the value property of the element, not the actual attribute of the tag. You can see more details on properties vs attributes in the answers to this question. Importantly for your case, when viewing the DOM through Chrome's dev tools, you are seeing the actual attributes, not the properties which are derived from them. There is no straightforward way that I know of to view properties through chrome's dev tools, except by executing javascript through the console (using the same concept as your alert() statement).

Community
  • 1
  • 1
David Sherron
  • 153
  • 1
  • 7