简体   繁体   中英

Why is the jquery method html() still have old content when using val() to update input value

   <div id="test-node">
         <input id="input-test" type="text" name="" value="old old old">
   </div

……

$("#input-test").val("new new new");
console.log($("#input-test").html());

The console log is <input id="input-test" type="text" name="" value="old old old">

Why does val() not update the input vallue? When I use attr() , it does work well.

The val() method will just update the value property of the element and not the value attribute.

To get the current value use val() method without any argument.

$("#input-test").val("new new new");
// to get the value use the val() method
console.log($("#input-test").val());

 $("#input-test").val("new new new"); console.log($("#input-test").val()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test-node"> <input id="input-test" type="text" name="" value="old old old"> </div> 


To reflect in HTML code update the attribute using attr() method.

 $("#input-test").attr('value', "new new new"); console.log($("#itest-node").html()); 

 $("#input-test").attr('value', "new new new"); console.log($("#input-test")[0].outerHTML); console.log($("#test-node").html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test-node"> <input id="input-test" type="text" name="" value="old old old"> </div> 

$("#input-test").val("new new new");

This line of code updates the value of the input , not change the element itself. Since you execute this function, you will notice on the browser screen that input will have a value new new new

If you want to change to value attribute of the input element, you should do something like:

$("#input-test input").attr("value", "new new new");

Why? Because the value attribute and the value property of an element are not the same once any user input or programmatic changes are made

The value attribute is only used by browser to be able to set the value property if applicable.

Try using val() as getter:

$("#input-test").val("new new new");
console.log($("#input-test").val());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM