0

I have a very simple html field

 <input type="text" value="#123456" name="color">

And basic jQuery code to change the value

 $(document).ready(function(){
     $('input').val('#AAAAAA');
 });

If I run this previous code, the display updates the value, but if I inspect the HTML element, it is still set to the old value. I have to do

 $(document).ready(function(){
     $('input').attr('value', '#AAAAAA');
 });

to actually change the input value. I was under the impression that val() would take care of updating the value if the input field has a name attribute, but it does not. Is this expected jQuery (3.4.1) behavior ?

Fiddle is here

steveso
  • 157
  • 2
  • 8
  • 2
    Here's a simple explanation of that behavior: https://stackoverflow.com/questions/7986026/html-input-is-not-updating-value-attribute-on-change#answer-7986111 – ThS Oct 13 '22 at 15:07
  • absolutely horrendous behavior, thanks for the link – steveso Oct 13 '22 at 15:10
  • attr("value", "#AAAAAA") changes the value here in the fiddle – steveso Oct 13 '22 at 15:15
  • The issue is that you have a misunderstanding of what "the value" is. You're changing the value attribute. – freedomn-m Oct 13 '22 at 15:16
  • adding upon @freedomn-m explanations, you may consider looking at the [`defaultValue`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#defaultvalue) property of an `input` element. – ThS Oct 13 '22 at 15:21

0 Answers0